I have IRepository<T> , and implementation SqlRepository<T>. SqlRepository has DataContext parameter in constructor.
SM configuration looks like this:
x.ForRequestedType(typeof(IRepository<>))
.TheDefaultIsConcreteType(typeof(SqlRepository<>));
x.ForRequestedType<DataContext>().CacheBy(InstanceScope.Hybrid)
.TheDefault.Is.ConstructedBy(()=>{
var dc = new FirstDataContext();
dc.Log = new DebuggerWriter();
return dc;
});
But for construction of IRepository<SpecificObject> i want to inject different DataContext. How do I say SM that when I ask for IReposiotry<SpecificObject> I want different DataContext, not FirstDataContext but SecondDataContext (that DC goes to different database).
For example, when I ask for IRepository<T> I want FirstDataContext to be injected, but when I ask explicity for IRepository<Product> I want SecondDataContext to be injected.
Also, that SecondDC should be Hybrid cached by SM!
Something like...
ForRequestedType<DataContext>()
.CacheBy(InstanceScope.Hybrid)
.AddInstances(inst => inst.ConstructedBy(() =>
new SecondDataContext { Log = new DebuggerWriter() })
.WithName("secondDataContext"))
.TheDefault.Is
.ConstructedBy(() => new FirstDataContext {Log = new DebuggerWriter()});
ForRequestedType<IRepository<SpecificObject>>()
.TheDefault.Is
.OfConcreteType<SqlRepository<SpecificObject>>()
.CtorDependency<DataContext>()
.Is(inst => inst.TheInstanceNamed("secondDataContext"));
That really helped me too. Have a concrete class used in a constructor that in turn gets a different connection string in its constructor depending on which "parent" class is using it. Thanks.
ObjectFactory.Initialize(x=>
{
// Different connection string for each usage
// of the RelationalGateway class
x.ForRequestedType<RelationalGateway>()
.AddInstances(r =>
r.ConstructedBy(() =>
new RelationalGateway(ConfigRepository.DataSourceName))
.WithName("config"))
.TheDefault.Is.ConstructedBy(
() => new RelationalGateway(OracleSpatialRepository.DataSourceName));
// Inject the right RelationalGateway
x.ForRequestedType<IConfigRepository>()
.TheDefault.Is.OfConcreteType<ConfigRepository>()
.CtorDependency<RelationalGateway>().Is(inst =>
inst.TheInstanceNamed("config"));
x.ForRequestedType<ISpatialRepository>()
.TheDefault.Is.OfConcreteType<OracleSpatialRepository>()
.CtorDependency<RelationalGateway>().IsTheDefault();
// Other simple types
x.ForRequestedType<IIdGenerator>().TheDefaultIsConcreteType<IdGenerator>();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With