如何在类库项目中使用Autofac?

时间:2011-02-01 12:49:43

标签: c# dependency-injection inversion-of-control ioc-container autofac

我有以下实现:

private INewsRepository newsRepository;

public NewsService(INewsRepository newsRepository)
{
     this.newsRepository = newsRepository;
}

此服务位于与我的Web项目不同的项目中。在哪里以及如何指定依赖注入?我还需要把它放在我的global.asax文件中吗?如果此服务也用于我的其他应用程序该怎么办?

3 个答案:

答案 0 :(得分:22)

您应该只从应用程序的根目录引用容器(global.asax)。这称为Register Resolve Release pattern

正确使用构造函数注入可确保您可以从其他应用程序重用NewsService类,而无需其他应用程序使用特定DI容器(或任何)。

这是designing the service in a DI Friendly manner的良好开端,但保持容器不可知

答案 1 :(得分:3)

[TestClass]
public class LogTest 
{
    /// <summary>
    /// Test project: autofac impl.
    /// </summary>
    private readonly ContainerBuilder _builder; 
    private readonly IContainer _container;

    /// <summary>
    /// Initializes a new instance of the <see cref="LogTest" /> class.
    /// </summary>
    public LogTest()
    {
        //
        // Read autofac setup from the project we are testing
        //
        _builder = new ContainerBuilder();
        Register.RegisterTypes(_builder);
        _container = _builder.Build();

        loggingService = _container.Resolve<ILoggingService>(new NamedParameter("theType", this));
    }

    [TestMethod]
    public void DebugMsgNoExectption()
    {
        var a = _container.Resolve<IHurraService>();
        var b = a.ItsMyBirthday();

public class HurraService : IHurraService
{
    private IHurraClass _hurra;

    /// <summary>
    /// Initializes a new instance of the <see cref="HurraService" /> class.
    /// </summary>
    public HurraService(IHurraClass hurra)
    {
        _hurra = hurra;
    }

    /// <summary>
    /// It my birthday.
    /// </summary>
    public string ItsMyBirthday()
    {
        return _hurra.Hurra();
    }
}

public static class Register
{
    public static void RegisterTypes(ContainerBuilder builder)
    {
        builder.RegisterType<LoggingService>().As<ILoggingService>();
        builder.RegisterType<HurraService>().As<IHurraService>();
        builder.RegisterType<HurraClass>().As<IHurraClass>();
    }
}

在类库中我创建了“Register”类。这里完成了Autofac设置。 在我的测试项目中,我读取了这个文件(Register.RegisterTypes)并初始化了_container。

现在我可以访问Resolve我正在测试的项目中的所有好东西。

答案 2 :(得分:2)

我想这取决于您是否打算在多个主机应用程序中使用相同的程序集。程序集是否真的需要引用AutoFac?我建议不要这样做,好像你的要求稍后改变,你会有大量不必要的引用。您的主机应用程序应该控制如何组装模块化部件,因此我将配置保留给您的主机(在这种情况下是您的Web应用程序。如果您想推动一些注册控制,您可以创建一个类型来处理您的注册,但正如我之前提到的,你的程序集基本上必然会使用AutoFac,例如:

public static class NewsRegistration()
{
    public static void RegisterTypes(ContainerBuilder builder)
    {
        // Register your specific types here.
        builder.RegisterType<NewsService>().As<INewsService>();
    }
}

这样你可以轻松打电话:

var builder = new ContainerBuilder();
// Register common types here?

NewsRegistration.RegisterTypes(builder);

var container = builder.Build();
相关问题