2017-04-13 85 views
3

有web-api2應用程序。共享庫中有一些自定義屬性(web-api應用程序引用此lib)。此外,該共享庫包含AppBuilderExtension(如app.UseMyCustomAttribute(新MySettings))是否可以在自定義OWIN中間件方法中註冊依賴項?

 public void Configuration(IAppBuilder app) 
    { 
     var httpConfiguration = new HttpConfiguration(); 

     ... 
     app.UseWebApi(httpConfiguration); 
     app.UseMyCustomAttribute(httpConfiguration, new MySettings() {Url = "https://tempuri.org"}); 
     ... 
    } 

屬性需要定製BL-服務的注入:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false, AllowMultiple = true)] 
public class MyAttribute : FilterAttribute, IAuthenticationFilter 
{ 
    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) 
    { 
     var myService = context.Request 
      .GetDependencyScope() 
      .GetService(typeof(IMyService)) as IMyService; 
     await _myService.DoSomething(); 
    } 

的問題是:是否有可能註冊IMyService在我的共享庫中使用UseMyCustomAttribute()擴展嗎?爲了這個目的,最好不要在共享庫中引用任何IoC庫(Autofac,Unity)。 (換句話說,不需要共享庫的消費者istantiate每個他們需要MyAttribute時間注入IMyService)喜歡的東西:

public static IAppBuilder UseMyCustomAttribute(this IAppBuilder app, HttpConfiguration config, MySettings settings) 
    { 
     config.Services.Add(typeof(IMyService), new MyService(settings.Url)); 
     return app; 
    } 

excception thrown

此方法拋出異常。 (如解釋here服務用於預定義的,衆所周知的服務。)如何在不使用任何DI/IoC庫(如Autofac,Unity等)的情況下將MyService添加到應用程序服務容器。在我的共享庫中實現UseMyCustomAttribute(...)方法的最佳解決方案是什麼?

修訂

我的問題不是:「如何註冊內屬性依賴」 (answered here)但是,如何註冊依賴項庫屬性?是否有可能在庫方法中實現,例如owin .UseMyAttribute()?我應該怎麼做註冊我的自定義IMyService屬性,在我的UseMyCustomAttribute()方法從上面?

+0

相關:https://stackoverflow.com/questions/4102138/how-to-use-dependency-injection-with-an-attribute – Steven

+0

@Steven我的問題不是關於:「如何註冊屬性內的依賴關係?」 (這裏回答)但是,如何註冊庫屬性的依賴關係?是否有可能在庫方法中實現,例如owin .UseMyAttribute()?我應該怎麼做才能在我上面的UseMyCustomAttribute()方法中註冊我的自定義IMyService屬性? –

回答

0

是否可以在我的共享庫的UseMyCustomAttribute()擴展中註冊IMyService?

是的,這是可能的,但你不應該。每個應用程序應該只有一個Composition Root,組合根應該通常爲not be reused。這意味着共享庫不應該有任何DI自舉邏輯,並且不應該依賴於DI庫。

+0

好吧,根據這個想法,在任何sahred庫中OWIN DependencyResolver的用法也是不好的風格?在這種情況下,我的情況是什麼正確的解決方案?在我的共享庫(靠近屬性類)中手動實現IMyService的普通舊singletone的實例化?附:你能否提供一個例子,說明我「不應該在我的共享庫中的UseMyCustomAttribute()擴展中註冊IMyService」,就像它可以如何完成的例子一樣。 –

+0

@ n.piskunov:您當前正在使用您的MyAttribute作爲Humble對象,並從DependencyScope中解析出IMyService,(這在[這裏]解釋過)(https://stackoverflow.com/a/29916075/264697 ))很好,如果你只有幾個這些屬性。這意味着你應該在Composition Root中註冊你的'MyService'(在你的情況下可能是'Configuration'方法)。這應該是你需要做的一切,或者是否有我從你的問題中遺漏的東西? – Steven

+0

謝謝你的幫助。我更新了我的問題,以更清晰的方式解釋我的問題。我的主要問題是 - 如何在庫方法UseMyCustomAttribute(...)中正確註冊MyService。一些代碼示例會特別有用。 –

相關問題