我在使用 Typed Factory 工具时遇到了一些非常意想不到的(我认为)行为。基本上,它重用瞬态组件实例进行构造函数注入Func<T>
。
这是它的要点:
// this guy is registered as service EntityFrameworkRepositoryProvider, not IRepository
[Transient]
public class EntityFrameworkRepositoryProvider : IRepository
{
public EntityFrameworkRepositoryProvider(ObjectContext objectContext, Assembly assembly)
{
// HOLY MOLY BATMAN!! Every time I hit this constructor when getProvider gets called,
// I don't actually get the arguments passed into getProvider. I get the
// arguments that were passed into getProvider the very FIRST time
// it was called...in other words I get the wrong
// ObjectContext (for the wrong connection string)...BIG PROBLEM
// do stuff...
}
}
[Singleton]
// this guy gets registered on startup
internal class EntityFrameworkRepositoryProviderFactory : IRepositoryProviderFactory
{
private readonly Func<ObjectContext, Assembly, EntityFrameworkRepositoryProvider> getProvider;
public EntityFrameworkRepositoryProviderFactory(Func<ObjectContext, Assembly, EntityFrameworkRepositoryProvider> getProvider)
{
this.getProvider = getProvider;
// do stuff...
}
public IRepository CreateRepository()
{
var provider = getProvider(new ObjectContext(GetConnectionString()),
Assembly.GetExecutingAssembly);
// do stuff...
}
public string GetConnectionString()
{
// returns one of a few diff EF connection strings
}
}
我也有一个标准的 LazyComponentLoader。我在这里做错了什么?我应该怎么做?
谢谢。