我是依赖注入(inject)模式的新手。我对一些事情有点困惑。
场景:
我有一个名为“MailCore”的类库项目。该项目具有执行所有电子邮件发送内容的接口(interface)和类。 我有一个名为“站点”的 MVC 项目。它使用“MailCore”项目发送电子邮件。我在这个项目中有 Unity,UnityContainer 已注册,一切正常。
我还有另一个名为“SiteRepo”的类库库项目。有时,为了执行某些特定任务,我必须从该项目发送电子邮件。因此,该项目中也引用了“MailCore”项目。
问题:
我已经在“SiteRepo”项目中从 NuGet 安装了 Unity,它似乎没有在这个类库项目中创建任何 UnityConfig。 我如何在此处注册 UnityContainer?
代码:
网站:
Public class JobController : Controller
{
private readonly IEmailBuilder mailBuilder;
public JobController(IEmailBuilder mailBuilder)
{
this.mailBuilder = mailBuilder;
}
public ActionResult Create(....)
{
JobRepo j = new JobRepo();
j.Create(....);
}
}
UnityConfig(这是在网络应用“The Site”中):
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>();
container.RegisterType<IEmailBuilder, EmailBuilder>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
站点 repo :
Public class JobRepo()
{
Public bool Create(...)
{
//some other code to create a job....
//have to send email using MailCore !! The problem area in concern..
}
}
最佳答案
如果您必须使用像 Unity 这样的 DI 容器(而不是 Pure DI ),您应该将它安装到您的 Composition Root 中,即“网站”。
从那里,您可以 reference the library projects并配置您的容器。
关于c# - 在类库项目中统一依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30877168/