10

我有以下實現:如何在類庫項目中使用Autofac?

private INewsRepository newsRepository; 

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

此服務是比我的web項目的一個單獨的項目。我在哪裏以及如何指定依賴注入?我仍然需要把它放在我的global.asax文件中嗎?如果此服務也用於其他應用,該怎麼辦?

回答

18

您應該只從應用程序的根引用容器(global.asax)。這就是所謂的Register Resolve Release pattern

您正確使用構造函數注入可確保您可以重新使用來自其他應用程序的NewsService類而不要求這些其他應用程序使用特定的DI容器(或任何其他應用程序)。

這是一個良好的開端designing the service in a DI Friendly manner,但保持它容器不可知論者

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(); 
2
[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>(); 
    } 
} 

在類庫內部我創建了「註冊」類。這裏Autofac設置完成。 在我的測試項目中,我讀取這個文件(Register.RegisterTypes)並初始化_container。

現在我可以訪問解決我正在測試的項目中的所有好東西。

相關問題