Ben*_*ter 7 structuremap nhibernate asp.net-mvc dependency-injection
我之前提出过这个问题,但我仍然在努力寻找一个可以让我理解的例子(请不要只是告诉我看看S#arp架构项目,至少没有一些方向).
到目前为止,我已经在我的网络项目中实现了近乎持久的无知.我的存储库类(在我的数据项目中)在构造函数中使用了一个ISession:
public class ProductRepository : IProductRepository
{
private ISession _session;
public ProductRepository(ISession session) {
_session = session;
}
Run Code Online (Sandbox Code Playgroud)
在我的global.asax中,我公开当前会话,并在beginrequest和endrequest上创建和处理会话(这是我对NHibernate的依赖):
public static ISessionFactory SessionFactory = CreateSessionFactory();
private static ISessionFactory CreateSessionFactory() {
return new Configuration()
.Configure()
.BuildSessionFactory();
}
protected MvcApplication() {
BeginRequest += delegate {
CurrentSessionContext.Bind(SessionFactory.OpenSession());
};
EndRequest += delegate {
CurrentSessionContext.Unbind(SessionFactory).Dispose();
};
}
Run Code Online (Sandbox Code Playgroud)
最后我的StructureMap注册表:
public AppRegistry() {
For<ISession>().TheDefault
.Is.ConstructedBy(x => MvcApplication.SessionFactory.GetCurrentSession());
For<IProductRepository>().Use<ProductRepository>();
}
Run Code Online (Sandbox Code Playgroud)
看来我需要我自己的ISession和ISessionFactory的通用实现,我可以在我的web项目中使用它并注入我的存储库?
所以只是为了澄清 - 我在我的存储库层使用NHibernate并希望使用session-per-(http)请求.因此,我正在向我的存储库构造函数中注入一个ISession(使用structuremap).目前,为了在每个请求中创建和处理会话,我必须从我的web项目中引用NHibernate.这是我想要删除的依赖项.
谢谢,本
为什么不创建一个 IHttpModule 并在那里执行创建和处理(可能在 Begin_Request 和 End_Request 事件中),而是将 IHttpModule 放入具有 NHibernate 依赖项的项目中。例如。
namespace MyWebApp.Repository.NHibernateImpl
{
public class NHibernateModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Context_BeginRequest);
context.EndRequest += new EventHandler(Context_EndRequest);
}
private void Context_BeginRequest(object sender, EventArgs e)
{
// Create your ISession
}
private void Context_EndRequest(object sender, EventArgs e)
{
// Close/Dispose your ISession
}
public void Dispose()
{
// Perhaps dispose of your ISessionFactory here
}
}
}
Run Code Online (Sandbox Code Playgroud)
也许有更好的方法,我也有兴趣知道这一点,所以有其他建议吗?
归档时间: |
|
查看次数: |
5773 次 |
最近记录: |