确保控制器具有无参数的公共构造函数错误

我遵循了本教程,该教程效果很好,直到我修改了我的教程DbContext以拥有其他构造函数。我现在在分辨率方面遇到问题,不确定如何解决此问题。有没有一种简单的方法可以强制它获取无参数的构造函数,或者我处理方法不正确?


DbContext 有两个构造函数:


public class DashboardDbContext : DbContext

{

    public DashboardDbContext() : base("DefaultConnection") { }


    public DashboardDbContext(DbConnection dbConnection, bool owns)

        : base(dbConnection, owns) { }

}

SiteController 构造函数:


private readonly IDashboardRepository _repo;


public SiteController(IDashboardRepository repo)

{

    _repo = repo;

}

仓库:


DashboardDbContext _context;


public DashboardRepository(DashboardDbContext context)

{

    _context = context;

}

UnityResolver 码:


public class UnityResolver : IDependencyResolver

{

    private readonly IUnityContainer _container;


    public UnityResolver(IUnityContainer container)

    {

        _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:


var container = new UnityContainer();

container.RegisterType<IDashboardRepository, DashboardRepository>(new HierarchicalLifetimeManager());

config.DependencyResolver = new UnityResolver(container);

一只甜甜圈
浏览 1099回答 3
3回答

慕姐8265434

发生的事情是您被这个问题咬了。基本上,发生的事情是您没有在容器中显式注册控制器。Unity尝试为您解析未注册的具体类型,但是由于无法解析(由于配置错误导致),因此它返回null。由于IDependencyResolver合同规定,Web API强制其返回null,因此它被迫返回null 。由于Unity返回null,因此Web API将尝试创建控制器本身,但是由于它没有默认构造函数,因此它将引发“确保控制器具有无参数公共构造函数”异常。此异常消息具有误导性,没有解释真正的原因。如果您显式注册控制器,您会看到一条更清晰的异常消息,这就是为什么您应该始终显式注册所有根类型的原因。但是,当然,配置错误是由于您在中添加了第二个构造函数而引起的DbContext。Unity总是尝试选择参数最多的构造函数,但是它不知道如何解析这个特定的构造函数。因此,真正的原因是您试图使用Unity的自动装配功能来创建DbContext。DbContext是一种特殊类型,不应自动接线。这是一种框架类型,因此您应该回退到使用工厂委托进行注册:container.Register<DashboardDbContext>(&nbsp; &nbsp; new InjectionFactory(c => new DashboardDbContext()));&nbsp;

摇曳的蔷薇

我遇到了同样的问题,我通过在UnityConfig.cs文件中进行更改来解决了该问题。为了解决UnityConfig.cs文件中的依赖项问题,您必须添加:public static void RegisterComponents()&nbsp; &nbsp;&nbsp;{&nbsp; &nbsp; var container = new UnityContainer();&nbsp; &nbsp; container.RegisterType<ITestService, TestService>();&nbsp; &nbsp; DependencyResolver.SetResolver(new UnityDependencyResolver(container));}
打开App,查看更多内容
随时随地看视频慕课网APP