有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;
}
此方法拋出異常。 (如解釋here服務用於預定義的,衆所周知的服務。)如何在不使用任何DI/IoC庫(如Autofac,Unity等)的情況下將MyService添加到應用程序服務容器。在我的共享庫中實現UseMyCustomAttribute(...)方法的最佳解決方案是什麼?
修訂
我的問題不是:「如何註冊內屬性依賴」 (answered here)但是,如何註冊依賴項爲庫屬性?是否有可能在庫方法中實現,例如owin .UseMyAttribute()?我應該怎麼做註冊我的自定義IMyService屬性,在我的UseMyCustomAttribute()方法從上面?
相關:https://stackoverflow.com/questions/4102138/how-to-use-dependency-injection-with-an-attribute – Steven
@Steven我的問題不是關於:「如何註冊屬性內的依賴關係?」 (這裏回答)但是,如何註冊庫屬性的依賴關係?是否有可能在庫方法中實現,例如owin .UseMyAttribute()?我應該怎麼做才能在我上面的UseMyCustomAttribute()方法中註冊我的自定義IMyService屬性? –