I would like to pass values into the constructor on the class that implements my service.
However ServiceHost only lets me pass in the name of the type to create,
Screw it… I blended the dependency injection and service locator patterns (but mostly it's still dependency injection and it even takes place in the constructor which means you can have read-only state).
public class MyService : IMyService
{
private readonly Dependencies _dependencies;
// set this before creating service host. this can use your IOC container or whatever.
// if you don't like the mutability shown here (IoC containers are usually immutable after being configured)
// you can use some sort of write-once object
// or more advanced approach like authenticated access
public static Func GetDependencies { get; set; }
public class Dependencies
{
// whatever your service needs here.
public Thing1 Thing1 {get;}
public Thing2 Thing2 {get;}
public Dependencies(Thing1 thing1, Thing2 thing2)
{
Thing1 = thing1;
Thing2 = thing2;
}
}
public MyService ()
{
_dependencies = GetDependencies(); // this will blow up at run time in the exact same way your IoC container will if it hasn't been properly configured up front. NO DIFFERENCE
}
}
The dependencies of the service are clearly specified in the contract of it's nested Dependencies
class. If you are using an IoC container (one that doesn't already fix the WCF mess for you), you can configure it to create the Dependencies
instance instead of the service. This way you get the warm fuzzy feeling that your container gives you while also not having to jump through too many hoops imposed by WCF.
I'm not going to lose any sleep over this approach. Neither should anyone else. After all, you're IoC container is a big, fat, static collection of delegates that creates stuff for you. What's adding one more?