I have an interface, called IRepository, with two implementations:
SqlRepository
SqlDualWriterRepository
The first implementation is a regular SQL persistence implementation for objects of type T. It has a dependency on an instance of SqlConnectionStringProvider (which provides a connection string, as the name suggests and takes as constructor parameter a connection string name ).
The second is another implementation that uses internally two SQLRepository dependencies:
public class SqlDualWriterRepository<T> : IRepository<T>
{
private readonly IRepository<T> _primaryRepository;
private readonly IRepository<T> _secondaryRepository;
public SqlDualWriterRepository(
IRepository<T> primaryRepository,
IRepository<T> secondaryRepository)
{
_prima开发者_运维百科ryRepository = primaryRepository;
_secondaryRepository = secondaryRepository;
}
}
What I want to achieve is configure StructureMap so that when asking for an IRepository instance, it will:
- resolve IRepository to an instance of SqlDualWriterRepository
- resolve the two inner repositories to type SqlRepository
- for the two SqlRepository objects instantiated at step 2 I need to resolve the SqlConnectionStringProvider in a different way (providing different string parameters in the constructor)
I have no idea how to achieve this. Is there a way to do it with Attributes or other types of configuration?
I'm using StructureMap 2.6.2.0.
I found two solutions:
Using a lambda to tell StructureMap how to build the SqlDualWriterRepository instance that will solve IRepository dependencies:
x.For<IRepository<Type>>().Use( ()=> new SqlDualWriterRepository<Type>( NewPrimaryRepositoryInstance<Type>(), NewSecondaryRepositoryInstance<Type>()));
Using .Ctor<>() to explicitly specify what to instantiate for each constructor dependency:
x.For<IRepository<Type>>().Use<SqlDualWriterRepository<Type>>() .Ctor<IRepository<Type>>("primaryRepository").Is(NewPrimaryRepositoryInstance<Type>()) .Ctor<IRepository<Type>>("secondaryRepository").Is(NewSecondaryRepositoryInstance<Type>());
In both examples above, the NewPrimaryRepositoryInstance() and NewSecondaryRepositoryInstance() methods create the primary and secondary SqlRepositories with the appropriate SqlConnectionStringProvider configurations.
There are probably better ways to achieve this, but these solutions do it for now.
精彩评论