Unity的依赖项注入可在控制器和Web API中使用,但不适用于某些区域

时间:2019-05-04 06:36:05

标签: c# asp.net-mvc-5 unity-container

嗨,我在我的项目中使用Unity for DI。我在项目名称“ Admin”和“ User”中有两个区域。一切正常,除非我在“ Admin”区域的控制器中使用DI。 “为此对象定义的无参数构造函数”。尽管它在WebApi和我所在区域之外的控制器中都可以正常工作

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        // register all your components with the container here
        // it is NOT necessary to register your controllers

        // e.g. container.RegisterType<ITestService, TestService>();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        container.RegisterType<IEmailSender, SendEmailFromGmail>();
    }
}




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

1 个答案:

答案 0 :(得分:0)

您在“管理员”控制器中的方法未受到DI的攻击。他们设置类的构造函数。因此,在这种情况下,您的DI无用。我建议您使用简单的Injector或使用Autofac或Ninject。