views:

129

answers:

1

I'm trying to hock up WCF with dependecy injection. All the examples that I have found is based on the assumptions that you either uses a .svc (ServiceHostFactory) service or uses app.config to configure the container. Other examples is also based on that the container is passed around to the classes.

I would like a solution where the container is not passed around (not tightly coupled to Unity). Where I don't uses a config file to configure the container and where I use self-hosted services.

The problem is - as I see it - that the ServiceHost is taking the type of the service implementation as a parameter so what different does it do to use the InstanceProvider?

The solution I have come up with at the moment is to register the ServiceHost (or a specialization) an register a Type with a name ( e.g. container.RegisterInstance<Type>("ServiceName", typeof(Service);).

And then container.RegisterType<UnityServiceHost>(new InjectionConstructor(new ResolvedParameter<Type>("ServiceName"))); to register the ServiceHost.

Any better solutions out there? I'm I perhaps way of in my assumptions.

Best regards,
Michael

+1  A: 

Use Constructor Injection to wire up your service implementation, just like you would with any other class.

Here's a writeup on how to make WCF understand Constructor Injection.

The example in that answer demonstrates Poor Man's Injection, but you can extrapolate from it and set up your UnityContainer instance in the ServiceHostFactory instead of a hard-coded dependency.

You pass the container instance all the way to the custom IInstanceProvider. Now you can use the container in the GetInstance method:

public object GetInstance(InstanceContext instanceContext)
{
    var serviceType = instanceContext.Host.Description.ServiceType;
    return this.container.Resolve(serviceType);
}
Mark Seemann
Yeah, I don't like passing around the container. I will try using generics instead.
Michael
At what point in time is the GetInstance called on the InstanceProvider? When I open the service host?
Michael
You would only be passing the container around in those three WCF classes (ServiceHostFactory, ServiceHost and IInstanceProvider). That's hardly the Service Locator anti-pattern - it's just DI infrastructure. You could even create a general-purpose library that wraps around Unity. Castle Windsor's WcfFacility does just that. To answer your other question: GetInstance is called every time a service operation is invoked.
Mark Seemann