Using Unity with Web Api 2 gives error does not have a default constructor

好久不见. 提交于 2019-12-06 06:09:34
smoksnes

I tend to use the Unity.Mvc-package.

You do not need to register the controllers, but you need to register Unity with WebAPI.

   public class UnityConfiguration()
   {
       public IUnityContainer Config()
       {
            IUnityContainer container = new UnityContainer();
            container.RegisterType<IMyService, Myservice>();
            container.RegisterType<IGenericRepository, GenericRepository>();
            container.RegisterType<DbContext, MyEntities>(); 

            // return the container so it can be used for the dependencyresolver.  
            return container;         
       }
    }

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Your routes...

            // Register Unity with Web API.
            var container = UnityConfiguration.Config();
            config.DependencyResolver = new UnityResolver(container);

            // Maybe some formatters?
        }
    }

You also need a DependencyResolver:

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();
    }
}

You can also take a look at this similiar question, except for the Owin-part. Unity.WebApi | Make sure that the controller has a parameterless public constructor

I had the same error and in my case the problem was, that i forgot to register a dependency that one of the classes, I had registered for dependency injection, injects in the constructor.

In your example, could it be that you inject something into MyEntities that you forgot to Register?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!