我在ASP.NET MVC应用程序上使用StructureMap和Entity Framework以及IRepository / IUnitOfWork模式。目标是将所有对象限定为当前HTTP请求,如下所示:
For<ObjectContext>()
.HttpContextScoped()
.Use<MembershipEntities>()
.Ctor<string>("connectionString")
.Is("name=MembershipEntities")
.Named(MembershipObjectContextInstanceKey);
For<IObjectContext>()
.HttpContextScoped()
.Use<ObjectContextAdapter>()
.Ctor<ObjectContext>("objectContext")
.Is(c => c.GetInstance<ObjectContext>(MembershipObjectContextInstanceKey))
.Named(MembershipIObjectContextInstanceKey);
For<IUnitOfWork>()
.HttpContextScoped()
.Use<UnitOfWork>()
.Ctor<IObjectContext>("objectContext")
.Is(x => x.GetInstance<IObjectContext>(MembershipIObjectContextInstanceKey))
.Named(MembershipUOWInstanceKey);
For(typeof(IRepository<>))
.HttpContextScoped()
.Use(typeof(Repository<>))
.CtorDependency<IObjectContext>("objectContext")
.IsNamedInstance(MembershipIObjectContextInstanceKey)
.Named(MembershipIRepositoryInstanceKey);
但是,当我运行此代码并获取IRepository和IUnitOfWork的命名实例时,它们的内部IObjectContexts不是同一个实例,这不是我的意图。
关于我做错的任何想法?任何帮助都将非常感激!
答案 0 :(得分:0)
StructureMap支持两种形式的依赖注入:
- 构造函数注入 - 通过构造函数参数将“依赖”推入具体类中。
- Setter Injection - 通过公共属性将依赖项“推送”到具体类中。 “Setter”命名法取自 Java的属性是getSomething()和setSomething(value)。
醇>
我使用类似于以下的配置获得了很好的结果:
// In my projects, I have something like a DataContext (IDataContext's implementation) expose my ObjectContext...
// * You don't need to HttpContextScope everything, usually the ObjectContext is sufficient
For<ObjectContext>()
.HttpContextScoped()
.Use<MembershipEntities>()
.Ctor<string>("connectionString")
.Is("name=MembershipEntities")
.Named(MembershipObjectContextInstanceKey);
// Usually, I don't abstract or wrap the ObjectContext, it is simply injected, under the hood
// ObjectContextAdapter receives an ObjectContext (HttpContextScoped)
For<IObjectContext>().Use<ObjectContextAdapter>();
// Ctor receives a IObjectContext
// * Again, if you have absolutely no use for IObjectContext, it shouldn't exist and UnitOfWork's ctor should receive the HttpContextScoped ObjectContext
For<IUnitOfWork>().Use<UnitOfWork>();
// Ctor receives a IObjectContext [...]
For(typeof(IRepository<>)).Use(typeof(Repository<>));
这或多或少都是我每次都这样做的。
让我知道它是否适合您。 此致 最大