Is it possible to register a dependency inside a custom OWIN-middleware method?

There is a web-api2 application. There is some custom attribute in the shared folder (the web-api application links to this lib). In addition, this shared library contains AppBuilderExtension (e.g. 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 requires the input of a 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();
    }

      

Question: is it possible to register an IMyService right inside the UseMyCustomAttribute () extension in my shared library? It is advisable not to reference the IoC libs (Autofac, Unity) in the shared lib for this purpose. (In other words, the consumers of the shared library are not required to istantiate and inject the IMyService every time they needed 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;
    }

      

excception thrown

This method throws an exception. (As explained here, Services are for predefined, known services.) How can I add MyService to an App Service container without using any DI / IoC libs (like Autofac, Unity, etc.). What's the best solution for implementing my UseMyCustomAttribute (...) method in my shared library?

UPDATED

My question is not about: "How do I register a dependency inside an attribute?" ( answered here ). But, how do I register a library attribute for . Is it possible to do this in library methods like owin.UseMyAttribute ()? What should I do to register my own IMyService for the attribute, inside the UseMyCustomAttribute () method on top?

+3


source to share


1 answer


Is it possible to register an IMyService right inside the UseMyCustomAttribute () extension in my shared library?



Yes, it is possible, but you shouldn't. Each application should only have one Root of Composition , and Roots of a composition should generally not be reused . This means that shared libraries should not have any DI bootstrap logic and should not have dependencies on the DI library.

0


source







All Articles