Ninject / NHibernate配置多个数据库;绑定到提供程序Ninject.Web.MVC3和.NET 4.5时可以使用多个绑定

时间:2017-08-31 22:20:51

标签: c# asp.net-mvc nhibernate ninject ninject.web.mvc

我尝试在混音中添加第二个数据库连接时出现问题。

错误:

enter image description here

NinjectConfigurator.cs

当我注释掉sybase db的绑定时,我没有收到任何错误。我试图在绑定.WhenClassHas<CLASS>()上设置条件ISessionFactory无效。

...
container.Bind<ISessionFactory>().ToProvider<MsSqlSessionFactoryProvider>().InSingletonScope().Named("mssql");
container.Bind<ISession>().ToProvider<MsSqlSessionProvider>().WhenClassHas<MsSqlNhibernateSessionAttribute>().InRequestScope();

container.Bind<ISessionFactory>().ToProvider<SybaseSessionFactoryProvider>().InSingletonScope().Named("sybase");
container.Bind<ISession>().ToProvider<SybaseSessionProvider>().WhenClassHas<NhibernateSessionAttribute>().InRequestScope();

container.Bind<ICurrentSessionContextAdapter>().To<CurrentSessionContextAdapter>();
...

MsSqlSessionFactoryProvider.cs

public class MsSqlSessionFactoryProvider : Provider<ISessionFactory>
{
    protected override ISessionFactory CreateInstance(IContext context)
    {
        return FluentNHibernate.Cfg.Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2012.ConnectionString(c => c.FromConnectionStringWithKey("MsSqlDbConnection")))
            .CurrentSessionContext("web")
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<SqlCommandFactory>())
            .BuildSessionFactory();
    }
}

MsSqlSessionProvider.cs

public class MsSqlSessionProvider : Provider<ISession>
{
    protected override ISession CreateInstance(IContext context)
    {
        var sessionFactory = context.Kernel.Get<ISessionFactory>("mssql");

        if (!CurrentSessionContext.HasBind(sessionFactory))
        {
            var session = sessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);
        }
        return sessionFactory.GetCurrentSession();
    }
}

SybaseSessionFactoryProvider.cs

public class SybaseSessionFactoryProvider : Provider<ISessionFactory>
{
    protected override ISessionFactory CreateInstance(IContext context)
    {
        return FluentNHibernate.Cfg.Fluently.Configure()
            .Database(
                OdbcConfiguration.Sybase.ConnectionString(c => c.FromConnectionStringWithKey("dbConnection")))
            .ExposeConfiguration(c => c.SetProperty(NHibernate.Cfg.Environment.Hbm2ddlKeyWords, "none"))
            .CurrentSessionContext("web")
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<OdbcCommandFactory>())
            .BuildSessionFactory();
    }
}

SybaseSessionProvider.cs

public class SybaseSessionProvider : Provider<ISession>
{
    protected override ISession CreateInstance(IContext context)
    {
        var sessionFactory = context.Kernel.Get<ISessionFactory>("sybase");
        if (!CurrentSessionContext.HasBind(sessionFactory))
        {
            var session = sessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);
        }
        return sessionFactory.GetCurrentSession();
    }
}

更新:

MsSqlNhibernateSessionAttribute.cs

using System.Web.Mvc;

namespace Common
{
    public class MsSqlNhibernateSessionAttribute : ActionFilterAttribute/*, IActionFilter*/
    {
        private readonly IActionTransactionHelper _actionTransactionHelper;
        private readonly IActionExceptionHandler _actionExceptionHandler;

        public MsSqlNhibernateSessionAttribute()
            : this(WebContainerManager.Get<IActionTransactionHelper>(),
                  WebContainerManager.Get<IActionExceptionHandler>())
        {
        }

        public MsSqlNhibernateSessionAttribute(
            IActionTransactionHelper actionTransactionHelper,
            IActionExceptionHandler actionExceptionHandler)
        {
            _actionTransactionHelper = actionTransactionHelper;
            _actionExceptionHandler = actionExceptionHandler;
        }

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            _actionTransactionHelper.BeginTransaction();
        }

        public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
        {
            _actionTransactionHelper.EndTransaction(actionExecutedContext);
            _actionTransactionHelper.CloseSession();
            _actionExceptionHandler.HandleException(actionExecutedContext);
        }
    }
}

NhibernateSessionAttribute.cs

using System.Web.Mvc;

namespace Common
{
    public class NhibernateSessionAttribute : ActionFilterAttribute
    {
        private readonly ISybaseActionTransactionHelper _sybaseActionTransactionHelper;
        private readonly IActionExceptionHandler _actionExceptionHandler;

        public NhibernateSessionAttribute()
            : this(WebContainerManager.Get<ISybaseActionTransactionHelper>(),
                  WebContainerManager.Get<IActionExceptionHandler>())
        {
        }

        public NhibernateSessionAttribute(
            ISybaseActionTransactionHelper actionTransactionHelper,
            IActionExceptionHandler actionExceptionHandler)
        {
            _sybaseActionTransactionHelper = actionTransactionHelper;
            _actionExceptionHandler = actionExceptionHandler;
        }

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            _sybaseActionTransactionHelper.BeginTransaction();
        }

        public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
        {
            _sybaseActionTransactionHelper.EndTransaction(actionExecutedContext);
            _sybaseActionTransactionHelper.CloseSession();
            _actionExceptionHandler.HandleException(actionExecutedContext);
        }
    }
}

我将它注入控制器并尝试将其注入ActionTransactionHelper类,但是当我这样做时,错误会更改为&#34;错误激活ISessionFactory。没有找到匹配的绑定......&#34;我包括控制器和一个ActionTransactionHelper,因为它们都是相同的实现(我不确定我是否可以拥有一个事务助手类)。

控制器

using System.Web.Mvc;
using Common;
using Data.SqlServer;
using NHibernate;
using Warehouse.Actions;
using Warehouse.Actions.VendorManagement;

namespace Warehouse.Controllers
{
    [MsSqlNhibernateSession]
    public class VendorManagementController : Controller
    {
        private readonly ISession _session;

        public VendorManagementController(ISession session) 
        {
            _session = session;
        }

        // GET: Vendor
        public ActionResult Index()
        {
            ViewVendorManagementAction viewVendorManagementAction = new ViewVendorManagementAction();
            return viewVendorManagementAction.Create(_session);
        }

        public ActionResult Vendor(Vendor vendor)
        {
            ViewVendorFormAction viewVendorFormAction = new ViewVendorFormAction();
            return viewVendorFormAction.Create(Request, _session);
        }

        public ActionResult SaveVendor(Vendor vendor)
        {
            SaveVendorAction saveVendorAction = new SaveVendorAction(_session);
            var newVendor = saveVendorAction.Save(vendor);
            var returnUrl = Url.Action("Vendor") + "?Id=" + newVendor.Id;
            return Redirect(returnUrl);
        }

        public ActionResult UpdateVendor(Vendor vendor)
        {
            UpdateVendorAction updateVendorAction = new UpdateVendorAction(_session);
            updateVendorAction.Update(vendor);
            var returnUrl = Url.Action("Vendor") + "?Id=" + vendor.Id;
            return Redirect(returnUrl);
        }
    }
}

ActionTransactionHelper.cs

using System.Web.Mvc;
using NHibernate;

namespace Common
{
    public class ActionTransactionHelper : IActionTransactionHelper
    {
        private readonly ISessionFactory _sessionFactory;
        private readonly ICurrentSessionContextAdapter _currentSessionContextAdapter;

        public ActionTransactionHelper(
            ISessionFactory sessionFactory,
            ICurrentSessionContextAdapter currentSessionContextAdapter)
        {
            _sessionFactory = sessionFactory;
            _currentSessionContextAdapter = currentSessionContextAdapter;
        }

        public void BeginTransaction()
        {
            var session = _sessionFactory.GetCurrentSession();

            if (session != null)
            {
                session.BeginTransaction();
            }
        }

        public bool TransactionHandled { get; private set; }

        public void EndTransaction(ActionExecutedContext filterContext)
        {
            var session = _sessionFactory.GetCurrentSession();
            if (session == null) return;
            if (!session.Transaction.IsActive) return;

            if (filterContext.Exception == null)
            {
                session.Flush();
                session.Transaction.Commit();
            }
            else
            {
                session.Transaction.Rollback();
            }

            TransactionHandled = true;
        }

        public bool SessionClosed { get; private set; }

        public void CloseSession()
        {
            if (_currentSessionContextAdapter.HasBind(_sessionFactory))
            { 
                var session = _sessionFactory.GetCurrentSession();
                session.Close();
                session.Dispose();
                _currentSessionContextAdapter.Unbind(_sessionFactory);

                SessionClosed = true;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

WhenClassHas<Attribute>绑定检查为类X注入绑定类型Y的类X.

例如,当你有一个绑定

Bind<IFoo>().To<Foo>().WhenClassHas<MarkerAttribute>();

[Marker]
public class Bar {
    public Bar(IFoo foo) ...
}

这令人满意。

然而,鉴于:

public class ZZZ
{
    public ZZZ(IFoo foo) ..
}

[Marker]
public class YYY {
    public YYY(ZZZ zzz) ..
}

满足条件。 IFoo被注入ZZZ,但没有[Marker]属性。

此外,当注入[Marker]属性本身时,这不满足条件,因为[Marker]属性本身在其类声明中没有[Marker]属性。

答案 1 :(得分:0)

我找到了解决问题的方法。感谢@BatteryBackupUnit的帮助。最后,我必须在ActionTransactionHelper中使用[Named(“从NinjectConfiguration绑定到ISessionFactory的相应名称”)装饰我注入的ISessionFactory)。

Ninject Documentation for contextual named bindings

例如:

在配置文件中使用.Named("name")

container.Bind<ISessionFactory>().ToProvider<MsSqlSessionFactoryProvider>().InSingletonScope().Named("mssql");

然后注入时,使用[Named(“name”)]

获取它
public class ActionTransactionHelper : IActionTransactionHelper
{
        private readonly ISessionFactory _sessionFactory;
        private readonly ICurrentSessionContextAdapter _currentSessionContextAdapter;

        public ActionTransactionHelper(
            [Named("mssql")] ISessionFactory sessionFactory,
            ICurrentSessionContextAdapter currentSessionContextAdapter)
        {
            _sessionFactory = sessionFactory;
            _currentSessionContextAdapter = currentSessionContextAdapter;
        }
}