类库中的 IoC.在哪里引导 [英] IoC in class library. Where to bootstrap

查看:23
本文介绍了类库中的 IoC.在哪里引导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个可以被其他组件重用的类库.在这个类库中,我使用 unity 进行依赖注入.对于这个类库,我创建了一个测试项目.调用者还会得到一个测试项目.我不确定的一件事是绑定的位置.我应该将其合并到类库中还是应该从调用应用程序中执行此操作?

I'm using a class library that can be reused by other components. In this class library I'm using unity for dependency injection. For this class library I create a test project. The caller also gets a test project. One thing I'm uncertain about is the location of the bindings. Should I incorporate this in the class library or should I do this from the calling application?

推荐答案

这是一个有趣的问题.您如何依赖注入没有入口点的可重用程序集.我真的很想看到其他人的回答.

This is an interesting problem. How can you dependency inject re-usable assemblies that do not have an entry point. I would really like to see other people's answer.

依赖注入是入口点程序集的责任.然而,如果您有很多类和程序集都需要 DI,那么它们可能会被某些类/程序集遗漏,从而使任务变得繁重.

Dependency injection is the responsibility of the entry-point assembly. Yet, if you have a lot of classes and assemblies each needing DI, then it is possible that they are left-off for some classes/assemblies and the task becomes onerous.

使用约定优于配置.您坚持使用 Foo 类实现 IFoo 等的规则.许多 DI 框架都可以使用约定来设置它.

Using convention over configuration. You stick to a rule of class Foo implementing IFoo, etc. A lot of DI frameworks have the means to set it up using convention.

上述解决方案并不能解决所有问题,因为有时您需要对注射设置进行参数化.以下是我解决问题的方法(特别是对于那些由 MEF 加载的程序集,这是针对 AutoFac 的):

Above solution does not solve all problems since sometimes you need to parameterise the setup of the injection. Here is how I have solved the problem (especially for those assemblies loaded by MEF and this is for AutoFac):

创建了一个接口IIocInstaller,容器(或构建器)在其中传递

Created an interface IIocInstaller where container (or builder is passed)

public interface IIocInstaller
{
    void Setup(ContainerBuilder builder);
}

创建了一个程序集属性来标记需要 DI 的程序集:

[AttributeUsage(AttributeTargets.Assembly)]
public class ExportAssemblyAttribute : Attribute
{
}

在每个程序集中,我创建一个设置 DI 的类:

[assembly: ExportAssembly]
namespace This.That
{

    [Export(typeof(IIocInstaller))]
    public class IocInstaller : IIocInstaller
    {
        public void Setup(ContainerBuilder builder)
        {
            ....
        }
    }
}

然后在入口点,我有一个通用代码,它查看所有已加载的具有程序集属性的程序集(包括 MEFed 程序集),然后查找实现 IIocInstaller 的类型,然后调用 Setup在他们身上.

Then in the entry point, I have a common code which looks through all loaded assemblies (including MEFed ones) that have the assembly attribute and then look for the type implementing the IIocInstaller and then call Setup on them.

这篇关于类库中的 IoC.在哪里引导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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