Brian Hjøllund
Brian Hjøllund

Reputation: 88

Using dependency injection on a type="" property

I'm currently in the process of refactoring our backend, and in the process, I've removed the dependency on a ServiceLocator. But! this has now given me the headache of figuring out how to do dependency injection, when the type that needs injecting, is pulled from Web.config The current, specific, case is this:

<system.identityModel>
    <identityConfiguration>
      <claimsAuthenticationManager type="MyNamespace.MyClaimsAuthenticationManager, MyAssembly, Version=1.0.0.0, Culture=neutral" />
      <claimsAuthorizationManager type="MyNamespace.MyClaimsAuthorizationManager, MyAssembly, Version=1.0.0.0, Culture=neutral" />
      <securityTokenHandlers>
        <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <securityTokenHandlerConfiguration maximumClockSkew="5"></securityTokenHandlerConfiguration>
      </securityTokenHandlers>
    </identityConfiguration>
</system.identityModel>

Here the types MyClaimsAuthenticationManager and MyClaimsAuthorizationManager are the ones that needs their dependencies injected.

The project is running under .NET 4.5, and currently using Ninject for the dependency injection part.

Upvotes: 2

Views: 81

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233150

You can't do DI with the Provider mechanisms in .NET, mainly because of its reliance on the Constrained Construction anti-pattern.

Your best option is to find a better design that doesn't rely on .NET's Provider mechanisms.

If that's impossible, your next-best option is to treat the Provider (in this case MyClaimsAuthenticationManager and MyClaimsAuthorizationManager) as Humble Objects that each contain a Composition Root that composes the actual object graph that does the work. In other words, you can view those Providers as Adapters over whatever object graph you need to spin up in order to do the actual work.

In my book, I cover this approach in more detail in section 7.5.

Upvotes: 4

Related Questions