Unity.WebApi - Make sure that the controller has a parameterless public constructor

时间:2019-06-01 14:07:35

标签: c# asp.net asp.net-web-api unity-container

I am currently working on an asp.net Web API project. The project consists of the following files: "S3BucketController", "IS3Service", "S3Service". Basically, I am trying to call the AmazonS3 web service to create and retrieve data. To make my code cleaner, I reference on the following article on dependency injection

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection

I am using the Unity.WebApi NuGet package (Unity 5.2.0 and Unity.WebApi 5.3.0) The issue I am facing is that when attempting to run the code, I get the error: Make sure that the controller has a parameterless public constructor. I've research similar issues in StackOverflow but still could not solve my issue.

Update I am still trying to solve this issue, any help is greatly appreciated

Below is my code: S3BucketController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Task_7.Services;


namespace Task_7.Controllers
{
    public class S3BucketController : ApiController
    {
        private readonly IS3Service _service;

        // Initialize at constructor
        // injected the IS3Service, 
        public S3BucketController(IS3Service service)
        {
            _service = service;
        }

        [HttpPost]
        [Route("api/S3Bucket/CreateBucket")]
        public async Task<IHttpActionResult> CreateBucket([FromBody] string bucketName)
        {
            var response = await _service.createBucketAsync(bucketName);
            return Ok(response);
        }

        [HttpPost]
        public async Task<IHttpActionResult> AddFile([FromBody] string bucketName)
        {
            await _service.createFileAsync(bucketName);
            return Ok();
        }   
    }
}

IS3Service

using System.Threading.Tasks;
using Task_7.Models;

namespace Task_7.Services
{
    public interface IS3Service
    {
        Task<S3Response> createBucketAsync(string bucketName);
        Task createFileAsync(string bucketName);
    }

S3Service

using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using Amazon.S3.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using Task_7.Models;

namespace Task_7.Services
{

    public class S3Service : IS3Service
    {
        private readonly IAmazonS3 _client;

        public S3Service(IAmazonS3 client)
        {
            _client = client;
        }

        public async Task<S3Response> createBucketAsync(string bucketName)
        {
            try
            {

                if (await AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName) == false)
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName = bucketName,
                        UseClientRegion = true
                    };

                    var response = await _client.PutBucketAsync(putBucketRequest);

                    return new S3Response
                    {
                        Message = response.ResponseMetadata.RequestId,
                        Status = response.HttpStatusCode
                    };
                }
            }
            catch (AmazonS3Exception e)
            {
                return new S3Response
                {
                    Status = e.StatusCode,
                    Message = e.Message
                };
            }

            catch (Exception e)
            {
                return new S3Response
                {
                    Status = HttpStatusCode.InternalServerError,
                    Message = e.Message
                };
            }

            return new S3Response
            {
                Status = HttpStatusCode.InternalServerError,
                Message = "Something Went Wrong"
            };
        }
        private const string filePath = "C:\\Users\\ randomguy1\\Desktop\\Project\\Background_Images";



        public async Task createFileAsync(string bucketName)
        {
            try
            {

                var fileTransferUtility = new TransferUtility(_client);


                await fileTransferUtility.UploadAsync(filePath, bucketName);




            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            //https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-install-assemblies.html#net-dg-nuget
        }
    }
}

UnityResolver.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Dependencies;
using Unity;
using Unity.Exceptions;

namespace Task_7.Resolver
{
    public class UnityResolver : IDependencyResolver
    {
        protected IUnityContainer container;

        public UnityResolver(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            this.container = container;
        }

        public object GetService(Type serviceType)
        {
            try
            {
                return container.Resolve(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return container.ResolveAll(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return new List<object>();
            }
        }

        public IDependencyScope BeginScope()
        {
            var child = container.CreateChildContainer();
            return new UnityResolver(child);
        }

        public void Dispose()
        {
            container.Dispose();
        }
    }
}

WebApiConfig.cs

using Amazon.S3;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Task_7.Resolver;
using Task_7.Services;
using Unity;
using Unity.Lifetime;

namespace Task_7
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            // Web API configuration and services 
            var container = new UnityContainer();
            container.RegisterType<IS3Service, S3Service>(new HierarchicalLifetimeManager());

            container.RegisterType<IAmazonS3>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);


            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

0 个答案:

没有答案
相关问题