How to inject dependencis into WCF Attribute with Simple Injector

You can't do constructor injection into attributes, because it is the CLR who is in control over the creation of attributes; not the DI library. Although you could initialize/build-up attributes after they have been created and inject dependencies using property injection, this is very risky for the following reasons:

  • Many frameworks cache attributes, which make them effectively singletons. This will cause Captive Dependencies in cases the dependencies themselves aren't singletons themselves.
  • It will be hard to impossible to let the container verify object graphs that start from the attributes, which might cause a false sense of security when verifying and diagnosing the container's configuration.

Instead, a much better approach is to either make attributes either passive or humble objects.

With a humble object, you extract all logic out of the attribute into its own service. The only code that will be left in the attribute is a call to your container or Service Locator to resolve that service and you call the method. This might look like this (excuse my C#):

public class AuthRequiredAttribute : Attribute, IOperationBehavior
{
    public object BeforeCall(string operationName, object[] inputs) {
        var checker = Global.Container.GetInstance<IAuthorizationChecker>();
        checker.Check();
    }
}

// Attribute's logic abstracted to a new service. This service can be
// registered, verified, diagnosed, and tested.
public class AuthorizationChecker : IAuthorizationChecker
{
    private readonly IDS authenticationService;
    public AuthorizationChecker(IDS authenticationService) {
        this.authenticationService = authenticationService;
    }

    public void Check() {
        if (this.authenticationService.Usuario == null) {
            if (HttpContext.Current == null) {
                throw new SecurityException();
            } else {
                throw new WebFaultException<string>();
            }
        }
    }
}

This requires you to expose the container in a way that your attributes can resolve the services they need. Advantage of this is that it is easy implemented, quite clean. Downside is that that you have to fall back to the Service Locator anti-pattern to get this working, and you have to make sure that your service is registered, because the container won't warn about this and this will, therefore, fail at runtime instead of during application startup of inside an integration test that calls container.Verify().

The second option is using passive attributes. This is especially useful when you have multiple of these attributes. This article describes the basic idea behind passive attributes and gives an example how to implement this in Web API. WCF has different interception points, so applying this to WCF requires a different implementation, but the concept stays the same.