IoC Register Instance Issue with MVC3, Unity & NHi

2019-07-13 15:10发布

问题:

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.