开发者

StructureMap configuration help

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:

  1. resolve IRepository to an instance of SqlDualWriterRepository
  2. resolve the two inner repositories to type SqlRepository
  3. 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:

  1. 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>()));
    
  2. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜