Create a WCF service's dependencies based on extra parameters
In our ASP.NET proje开发者_运维技巧ct we have a session manager service interface that we use to find out information about the current user. For example:
var actorId = _sessionManager.CurrentActivePerson.PersonId;
This session manager is provided to classes via constructor-based dependency injection.
Now, we have a WCF service that we would like to instantiate with different DI bindings depending on the situation:
- If the consumer has provided a username for the session, we would like to use a session manager that considers that user to be the current person.
- Otherwise, we want to somehow require a domain ID to be provided, use a session manager that is tied to the system person for that domain.
In order for this to work properly, we need to allow the consumer to provide a domain ID as an argument, although it is not specified as an argument of the service itself. We then need to be able to access this argument from a DI binding method while the HostFactory is creating the service instance.
Does anybody have any suggestions on how we might do this?
Notes:
- I already know how to create dependent bindings generally: the question is about passing this extra parameter to the service's factory.
- The WCF service is exposed as a SOAP endpoint, and uses certificate-based security.
This sounds to me to be an authentication/authorization issue more than a DI issue. If that is the case, the most correct low-level solution would actually be to implement a custom token.
That's a pretty complex task, so you should seriously consider switching to claims-based authorization. The Windows Identity Foundation provides a lot of tools to do this.
This would mean that instead of having to manage two fundamentally different security contexts (user name vs. domain id) you externalize the identity management so that you don't have to deal with such a cross-cutting concern inside the application code. This would give you a better separation of concerns.
However, if you truly need to defer the resolution of a dependency until the actual method call, the universal solution is to inject an abstract factory.
Just in case you need information about how to enable Constructor Injection for WCF, here's how: Injecting data to a WCF service
精彩评论