【发布时间】:2016-06-10 18:30:39
【问题描述】:
我有两个独立的项目...一个项目使用 Simple Injector,另一个项目使用 Unity。从简单的注入器项目中,我尝试使用 Unity 为其 DI 注册位于项目中的类的接口/实现。我可以成功地做到这一点并获得对该类的访问权限,但是该类中标记为 Unity [Dependency] 的任何内容都无法解决。我可以将这些依赖项注册到 Simple Injector 容器,但一旦使用 Unity 进入类,它就会丢失。
例子:
Project1(使用简单注入器)
public class StartUp {
var container = new Container();
container.RegisterSingleton(typeof(IGenericRepo<>), typeof(GenericRepo));
container.RegisterSingleton<IService, Service>();
//more code below etc...
}
public class TestController
{
private readonly IService service;
public TestController(IService service)
{
this.service = service;
}
public void TestMethod()
{
var test = service.GetEverything();
}
}
Project2(使用 Unity)
public class Service : IService
{
[Dependency]
public IGenericRepo<ServiceObj> _serviceRepo { private get; set; }
public IQueryable<ServiceObj> GetEverything()
{
return _serviceRepo.Get();
}
}
通过上面的示例,我可以访问项目 2 中的 GetEverything 方法,但是 _serviceRepo 依赖项为空。有没有办法让它知道使用 Project1 中注册的 GenericRepo?
这样可以吗?
谢谢! 瑞恩
【问题讨论】:
-
你在哪里注册你的 serviceRepo 在项目二?见:msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx
-
Project2 目前没有明确注册任何东西......到目前为止,唯一使用它的其他项目是其他 Unity 项目,其中注册是在 web.config 中完成的,或者在应用程序。
-
您可以将第一个项目的 dll 包含在第二个项目的引用中,然后注册它。
-
Project1其实是一个web服务(web api)
-
你真的不应该在你的类库中使用 DI 容器。看看这篇文章:blog.ploeh.dk/2011/07/28/CompositionRoot
标签: c# dependency-injection unity-container simple-injector