There is web-api2 application. There is some custom attribute inside shared lib (web-api application refers this lib). Besides, this shared lib contains AppBuilderExtension (like app.UseMyCustomAttribute(new MySettings))
public void Configuration(IAppBuilder app)
{
var httpConfiguration = new HttpConfiguration();
...
app.UseWebApi(httpConfiguration);
app.UseMyCustomAttribute(httpConfiguration, new MySettings() {Url = "https://tempuri.org"});
...
}
The attribute needs injection of custom BL-service :
[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();
}
The question is: Is it possible to register IMyService right inside UseMyCustomAttribute() extension in my shared library? It's desirable not to refer any IoC libs (Autofac, Unity) in shared lib for this purpose. (In other words, don't require consumers of shared library to istantiate and inject IMyService each time they need MyAttribute) Something like:
public static IAppBuilder UseMyCustomAttribute(this IAppBuilder app, HttpConfiguration config, MySettings settings)
{
config.Services.Add(typeof(IMyService), new MyService(settings.Url));
return app;
}
This method throws an exception. (As explained here Services is for predefined, well-known services.) How can I add MyService to applications service container, without using any DI/IoC libs (as Autofac, Unity and so on). What is the best solution to implement my UseMyCustomAttribute(...) method in my shared library?
UPDATED
My question is not about: "How to register dependency inside the attribute?" (answered here ) But, How to register dependency for library attribute? Is it possible to do it in library methods, such as owin .UseMyAttribute()? What should I do to register my custom IMyService for attribute, inside my UseMyCustomAttribute() method from above?
