StructureMap resolve dependency through injection instead of service location
- by Chris Marisic
In my project I register many ISerializers implementations with the assembly scanner. FWIW this is the code that registers my ISerializers
Scan(scanner =>
{
scanner.AssemblyContainingType<ISerializer>();
scanner.AddAllTypesOf<ISerializer>().NameBy(type => type.Name);
scanner.WithDefaultConventions();
});
Which then correctly registers
ISerializer (...ISerializer)
Scoped as: Transient
JsonSerializer Configured Instance of ...JsonSerializer
BsonSerializer Configured Instance of ...BsonSerializer
And so forth.
Currently the only way I've been able to figure out how to resolve the serializer I want is to hardcode a service location call with
jsonSerializer = ObjectFactory.GetNamedInstance<ISerializer>("JsonSerializer");
Now I know in my class that I specifically want the jsonSerializer so is there a way to configure a rule or similar that says for ISerializer's to connect the named instance based on the property name? So that I could have
MySomeClass(ISerializer jsonSerializer, ....)
And StructureMap correctly resolve this scenario? Or am I approaching this wrong and perhaps I should just register the concrete type that implements ISerializer and then just specifically use
MySomeClass(JsonSerializer jsonSerializer, ....)
for something along these lines with the concrete class?