Unity Dependency Injection仅在注入MVC​​ Controller时有效?

时间:2016-09-07 08:55:33

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

我希望将服务注入我创建的自定义类>我一直在使用依赖注入将相同的服务注入我的WebApi控制器,但似乎无法理解为什么它不能在我的" InputDataValidationModel"类

这就是我想要做的事情:

 public class InputDataValidationModel
{
    private  ISec300_EE_SubmissionRepository _service { get; set; }

    public InputDataValidationModel(ISec300_EE_SubmissionRepository service)
    {
        _service = service;
    } 
}    

在Global.asax中我注册了以下类型:

   protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        ConfigureApi(GlobalConfiguration.Configuration);
    }

    void ConfigureApi(HttpConfiguration config)
    {
        var unity = new UnityContainer();

        // Register the Controllers that should be injectable
        unity.RegisterType<SEC300_EE_SubmissionController>();
        unity.RegisterType<InputDataValidationModel>();

        unity.RegisterType<ISec300_EE_SubmissionRepository, Sec300_EE_SubmissionRepository>(new ContainerControlledLifetimeManager());
        unity.RegisterType<IClientRepository, ClientRepository>(new ContainerControlledLifetimeManager());

        // Finally, override the default dependency resolver with Unity
        config.DependencyResolver = new IoCContainer(unity);
    }

我无法理解的是,当我在下面的控制器中完成时,这非常有效:

public class SEC300_EE_SubmissionController : ApiController
{
    private ISec300_EE_SubmissionRepository _service;      
    public SEC300_EE_SubmissionController(ISec300_EE_SubmissionRepository service)
    {
        if (service == null)
        {
            throw new ArgumentNullException("service");
        }
        _service = service;
    }
}

1 个答案:

答案 0 :(得分:0)

它不起作用,因为控制器由Web API实例化,当Web API创建控制器时,它调用BeginScope,这是调用IoC的入口点,然后继续为您解析和构造对象。

在您的情况下InputDataValidationModel未使用,可能因为这个原因您没有实例

更新

Do you perhaps have any suggestions on how i would inject my service into InputDataValidationModel ?

选项1

您可以使用IDependencyResolver使用Unity容器查看此link依赖项解析''

在此之后,您可以像这样解决您的服务

var instance =GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof (InputDataValidationModel));

选项2 您可以使用服务定位器,即使它是反模式

static void Main(string[] args)
{            
    UnityServiceLocator locator = new UnityServiceLocator(ConfigureUnityContainer(
    ServiceLocator.SetLocatorProvider(() => locator);

    var a = ServiceLocator.Current.GetInstance<IFoo>();
    var b = ServiceLocator.Current.GetInstance<IFoo>();

    Console.WriteLine(a.Equals(b));            
}

private static IUnityContainer ConfigureUnityContainer()
{
    UnityContainer container = new UnityContainer();
    container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager());
    return container;
}

希望这个帮助