【问题标题】:Dependency Inject asp.net MVC4 Ninject依赖注入 asp.net MVC4 Ninject
【发布时间】:2014-09-09 00:15:10
【问题描述】:

这是我使用Ninject and MVC 的第一个项目,我正在尝试实施。

但我收到此错误:

激活 ISessionFactory 时出错

没有匹配的绑定可用,并且类型不是自绑定的。

激活路径:

3) 将依赖ISessionFactory注入PersonRepository类型的构造函数的参数会话中

2) 将依赖IPersonRepository 注入HomeController 类型的构造函数的参数personsRepository 1) 请求HomeController

Estou utilizando ISessionFactory no meu repositório, eu preciso dar bind nele?

我的仓库:

public class PersonRepository : IPersonRepository
{
    private ISession openSession;
    private ISessionFactory session;

    public PersonRepository(ISessionFactory session)
    {
        this.openSession = session.OpenSession();
        this.session = session;
    }

    public void CreatePerson(Person person)
    {
        openSession = NhibernateUtilities.OpenIfClosed(session, openSession);
        openSession.SaveOrUpdate(person);
    }

我的控制器:

    public class HomeController : Controller
    {

    private readonly IPersonRepository personsRepository;

    public HomeController(IPersonRepository personsRepository)
    {
        this.personsRepository = personsRepository;
    }

    public ActionResult Index()
    {
        Person test = new Person()
        {
            Id = 1,
            Name = "teste",
            Surname = "teste",
            Nickname = "teste",
            Age = 25,
            Division = "teste",
            Email = "teste",
            Lane = "teste"
        };

        personsRepository.CreatePerson(test);

        return View();
    }

Global.asax:

public class MvcApplication : NinjectHttpApplication
{
    protected override IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        kernel.Bind<IPersonRepository>().To<PersonRepository>();
        return kernel;
    }

    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

}

我正在使用Fluent Nhibernate

【问题讨论】:

  • 你在哪里为 ISession 设置绑定(或者是自动的?)而且看起来你不是在调用 CreateKernel。
  • 那么,ISessionFactory 有要绑定的存储库吗?它来自 Fluent 。我在教程中找到了这个 Create Kernel,我需要在某个地方调用它吗?
  • @RodrigoMagalhães Estou utilizando ISessionFactory no meu repositório, eu preciso dar bind nele? 将此行翻译成英文。

标签: asp.net asp.net-mvc asp.net-mvc-4 nhibernate ninject


【解决方案1】:

参考:Need help understanding how Ninject is getting a Nhibernate SessionFactory instance into a UnitOfWork?

你需要绑定会话工厂

Bind<ISession>().ToProvider<SessionProvider>().InRequestScope();

并在 repo 构造函数中使用 ISession

public class PersonRepository : IPersonRepository
{
    private ISession session;

    public PersonRepository(ISession session)
    {
        this.session = session;
    }

...

【讨论】: