When is the Unity InjectionConstructor acually run

2019-07-30 11:56发布

问题:

I have the following code:

IOC.Container.RegisterType<IRepository, GenericRepository>
              ("Customers", new InjectionConstructor(new CustomerEntities()));

What I am wondering is if the new CustomerEntities() will be called once when the type registration happens OR if every time IRepository (with name "Customers") is resolved a new CustomerEntities will be made.

If it is not the latter, then is there a way to make it work more like a delegate? (So it will make a new one every time it Resolves?)

I found this code:

IOC.Container.RegisterType<IRepository, GenericRepository>("Customers")
             .Configure<InjectedMembers>()
             .ConfigureInjectionFor<ObjectContext>
              (new InjectionConstructor(new CustomerEntities()));

I am not sure if that would do it or if that is just an old way of doing what my first code snippet does.

Any advice would be great!

回答1:

The code you have there runs once - a single CustomerEntities object is created at registration time, and that instance is shared as the parameter across all GenericRepository objects resolved later.

If you want a separate instance of CustomerEntities for each instance of GenericRepository, that's pretty easy - just let the container do the lifting. In the registration, do this:

IOC.Container.RegisterType<IRepository, GenericRepository>("Customers", 
    new InjectionConstructor(typeof(CustomerEntities)));

This will tell the container "When resolving IRepository, create an instance of GenericRepository. Call the constructor that takes a single CustomerEntities parameter. Resolve that parameter through the container.

This should do the trick. If you need to do special configuration in the container to resolve CustomerEntities, just do that with a separate RegisterType call.

The second example you showed is the obsolete API from Unity 1.0. Don't use it, it doesn't accomplish anything more than you can do with RegisterType now.