确保控制器在Unity中具有无参数的公共构造函数

Yar*_*lav 7 c# dependency-injection unity-container asp.net-mvc-4

我在控制器中遇到了这个问题:
尝试创建类型为' * .WebMvc.Controllers.HomeController' 的控制器时发生错误.确保控制器具有无参数的公共构造函数.

找到ApiController的解决方案,但没有找到任何关于普通Controller的信息.

从头开始创建新的MVC 4项目.

HomeController.cs:

public class HomeController : Controller
{
    private IAccountingUow _uow;
    public HomeController(IAccountingUow uow)
    {
        _uow = uow;
    }
Run Code Online (Sandbox Code Playgroud)

UnityDependencyResoler.cs:

public class UnityDependencyResolver : IDependencyResolver
{
    private IUnityContainer _container;
    public UnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
        RegisterTypes();
    }
    public object GetService(Type serviceType)
    {
        try
        {
            return _container.Resolve(serviceType);
        }catch
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.ResolveAll(serviceType);
        }catch
        {
            return null;
        }
    }

    private void RegisterTypes()
    {
        _container.RegisterType<IAccountingUow, AccountingUow>();

    }
}
Run Code Online (Sandbox Code Playgroud)

Global.asax中

    protected void Application_Start()
    {
        //Omitted
        DependencyResolver.SetResolver( new UnityDependencyResolver( new UnityContainer()));

    }
Run Code Online (Sandbox Code Playgroud)

调试并发现,甚至没有尝试解决IAccountingUow.

我做错了什么?整天思考它.

Yar*_*lav 6

发现问题在哪里.也许有人会面对同样的问题.问题是Unity无法解决IAccountingUow,因为接口的层次依赖性.

AccountingUow 班有两个控制器

    public AccountingUow( IRepositoryProvider repositoryProvider)
    {
        Init(repositoryProvider);
    }
    public AccountingUow()
    {
        Init( new RepositoryProvider(new RepositoryFactories()) );
    }
Run Code Online (Sandbox Code Playgroud)

依赖性解析器不应该采用默认的无参数构造函数.它尝试接受依赖于接口的构造函数并且无法解析它,因为没有解决它的规则.

我注释掉了依赖于接口的构造函数,一切正常.

我将在以后的解析器中发布第一个构造函数,也许有人会使用它.