在类库项目中实现统一性的依赖注入 [英] Dependency injection with unity in a class library project

查看:52
本文介绍了在类库项目中实现统一性的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是依赖注入模式的新手.我对几件事有些困惑.

I am new with the dependency injection pattern. I'm a little confused about few things.

我有一个名为"MailCore"的类库项目.该项目具有执行所有电子邮件发送内容的接口和类.我有一个名为站点"的MVC项目.它使用"MailCore"项目发送电子邮件.我在这个项目中有Unity,并且UnityContainer已注册,并且一切正常.

I have a class library project called 'MailCore'. This project has interfaces and classes that perform all email sending stuff. I have an MVC project called 'The site'. It uses the 'MailCore' project to send email. I have Unity in this project and the UnityContainer is registered and things are working fine.

我还有另一个名为"SiteRepo"的类库项目.有时,要执行某些特定任务,我必须从该项目发送电子邮件.因此,该项目中也引用了"MailCore"项目.

I also have another class library library project called 'SiteRepo'. Sometimes, to perform some specific tasks, I have to send email from this project. Therefore the 'MailCore' project is referenced in this project, too.

我已经在'SiteRepo'项目中从NuGet安装了Unity,并且在该类库项目中似乎没有创建任何UnityConfig.我如何在这里注册UnityContainer?

I have installed Unity from NuGet in the 'SiteRepo' project and it doesn't seem to create any UnityConfig in this class library project. How would I register a UnityContainer here?

TheSite:

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(位于Web应用程序站点"中):

UnityConfig (this is in the web app '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));
    }
}

SiteRepo:

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容器(而不是

If you must use a DI Container like Unity (instead of Pure DI), you should install it into your Composition Root, which is 'The site'.

从那里,您可以引用库项目并配置您的容器.

From there, you can reference the library projects and configure your container.

这篇关于在类库项目中实现统一性的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆