IoC Register Instance Issue with MVC3, Unity & NHibernate - (Unity.MVC3 lib from codeplex)

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 04:07:43

问题


I'm using the Unity.MVC3.dll from codeplex and am attempting to register an instance of a NHibernate ISession per request. As per the Unity MVC3 docs I should just have to use the HierarchicalLifetimeManager to accomplish this:

var container = new UnityContainer();
container.RegisterInstance<ISession>(SessionFactory.OpenSession(), new HierarchicalLifetimeManager());
container.RegisterControllers();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));

SessionFactory is a static object in my Global.asax. When I add ISession to one of my controllers I receive the following error message:

The current type, NHibernate.ISession, is an interface and cannot be constructed. Are you missing a type mapping?

I thought I didn't need to RegisterType when just registering an instance?

In my controller I have:

[Dependency]
public ISession session { get; set; }

I also tried adding ISession as an argument to one of my ActionResult functions

I'll add that the issue is not on NHibernate's end. The configuration is successful and I can use it to query info from my database.

UPDATE

When I do not specify the lifetime manager it works, however, this isn't going to get me my "one instance per request" that I need.

I might have to explore Ninject :p


回答1:


Try using registertype with an injection factory rather than registerinstance.

Something like:

Container.RegisterType<ISession>(new InjectionFactory(c => SessionFectory.OpenSession()), new HierarcicalLifetimeManager());



回答2:


If using MVC why not just use Constructor Injection so its passed into your controller when its instantiated. Thats the root of your request. I have working code for this if you are interested - I'll get it up here if so. Also just me, but I don't really like references where you have to put your concrete reference in code, much like is shown in the bootstrapper.cs code. With unity, your interface->concrete mappings can go in the config file.



来源:https://stackoverflow.com/questions/7771097/ioc-register-instance-issue-with-mvc3-unity-nhibernate-unity-mvc3-lib-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!