依赖注入asp.net MVC4 Ninject

时间:2014-09-09 00:15:10

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

这是我使用Ninject and MVC的第一个项目,我试图实现。

但是我收到了这个错误:

  

激活ISessionFactory

时出错      

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

激活路径:

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

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

Estou utilizando ISessionFactory nomeurepositó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

1 个答案:

答案 0 :(得分:2)

参考: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;
    }

...