Search code examples
c#wcfdependency-injectionautofac

How to use IServiceProvider in IServiceBehavior, IOperationBehaviour custom interfaces in WCF?


I have a custom .NET framework library which is used for different purposes like logging, security etc in my WCF application. Currently we make use of Autofac in both cases, for the library and the WCF application as well. But recently we decided to move out Autofac and use Microsoft.Extensions.DependencyInjection.Abstractions because consumers might want to use a different DI package. Changing stuff was easy until I started making changes to some attributes we use throughout application.

For example we have an attribute which looks like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false)]
public sealed class SecurityBehaviorAttribute : Attribute, IServiceBehavior, IOperationBehavior
{
    private readonly ISecurityManager _securityManager;

    public SecurityBehaviorAttribute()
    {
        _securityManager = AutofacHostFactory.Container.Resolve<ISecurityManager>();
    }

    //Implemented methods
}

Since we don't have AutofacHostFactory.Container in place anymore we need another way of getting these services but I am not sure if there is a way how to do this in WCF ?

While searching I found some info to create a custom IInstanceProvider which might help but still I am not sure how does it work because I did not find any example integrating it with abstraction package. Since in my top application we use Autofac.Integration.Wcf I think behind the scene this package creates a custom IInstanceProvider for internal needs, if so, how can I get this interface injected to my attribute and how to use it (this way the consumer would be responsible for creating a custom IInstanceProvider and I will just use it in my package)?

Another ugly solution would be to create a singleton instance of IServiceProvider and make use of it(not sure if it works well anyway)

To wrap it up:

  1. Is there a good/straightforward way how to resolve services in WCF attributes (like the one above) using only Microsoft.Extensions.DependencyInjection.Abstractions ?

  2. If 1) is not possible. Is there a way how to get IInstanceProvider which is created by top application(from consumer of package in this case) and use it here in the attribute ?

  3. Is creating a static object of IserviceProvider the only solution or there are other good ways without big changes ?


Solution

  • After trying so many ways I could not make anything else work except storing the IServiceProvider into a static property and reusing it.