StructureMap resolve dependency through injection instead of service location

Posted by Chris Marisic on Stack Overflow See other posts from Stack Overflow or by Chris Marisic
Published on 2010-03-28T01:47:13Z Indexed on 2010/03/28 1:53 UTC
Read the original article Hit count: 341

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about structuremap