问题
When using this object model:
interface IInterface {}
class Impl : IInterface
{
public Impl(int blah) {}
}
And this test:
void Test1()
{
IUnityContainer container = new UnityContainer();
container.RegisterInstance(new Impl(3), new ContainerControlledLifetimeManager());
container.RegisterType<IInterface, Impl>(new ContainerControlledLifetimeManager());
Impl impl = container.Resolve<Impl>();
}
I get an exception:
Resolution of the dependency failed, type = "BlahMain.Program+Impl", name = "(none)".Exception occurred while: while resolving.Exception is: InvalidOperationException - The type Int32 cannot be constructed. You must configure the container to supply this value.-----------------------------------------------At the time of the exception, the container was:Resolving BlahMain.Program+Impl,(none)Resolving parameter "blah" of constructor BlahMain.Program+Impl(System.Int32 blah)Resolving System.Int32,(none)
It looks like Unity is trying to construct its own Impl instance, even though I have already registered one.
Changing the registration order as follows:
void Test2()
{
IUnityContainer container = new UnityContainer();
// Note: RegisterInstance is now called after RegisterType.
container.RegisterType<IInterface, Impl>(new ContainerControlledLifetimeManager());
container.RegisterInstance(new Impl(3), new ContainerControlledLifetimeManager());
Impl impl = container.Resolve<Impl>();
}
solves the issue.
Now, changing the order of registrations is an acceptable workaround, but it forces me to think when setting up the container. I was hoping that when using Unity I wouldn't have to worry about registration order.
Can anyone explain this behavior? Is this such a delicate use-case that I have to be aware of registration order?
Damian,
This is what I'm trying to do and I'm getting the same error. Is this not what you meant?
void Test3()
{
IUnityContainer container = new UnityContainer();
var impl = new Impl(3);
container.RegisterInstance(impl, new ContainerControlledLifetimeManager());
container.RegisterInstance<IInterface>(impl, new ContainerControlledLifetimeManager());
container.RegisterType<IInterface, Impl>(new ContainerControlledLifetimeManager());
var resolvedImpl = container.Resolve<Impl>();
}
回答1:
You should do something like:
container.RegisterInstance<IInterface>(new Impl(3), new ContainerControlledLifetimeManager());
来源:https://stackoverflow.com/questions/5770580/resolve-may-fail-depending-on-order-of-registerinstance-and-registertype