问题
I'm trying to register the same type but with two different constructors. When I trying to resolve, I get "Resolution of the dependency failed" on the second Resolve.
var container = new UnityContainer();
container.RegisterType<IBar, Bar>()
.RegisterInstance(new Bar())
.RegisterType<IBar, Bar>()
.RegisterInstance(new Bar("foo"));
Bar bar1 = (Bar)container.Resolve<IBar>();
Bar bar2 = (Bar)container.Resolve<IBar>("foo"); // ERROR
What I'm doing wrong?
回答1:
You need to give them names when registering. The parameter to Resolve is the name of the instance you want.
var container = new UnityContainer();
container
.RegisterInstance<IBar>("BAR", new Bar())
.RegisterInstance<IBar>("FOOBAR", new Bar("foo"));
Bar bar1 = (Bar)container.Resolve<IBar>("BAR");
Bar bar2 = (Bar)container.Resolve<IBar>("FOOBAR");
来源:https://stackoverflow.com/questions/870470/how-to-register-same-type-twice-with-different-constructors-in-unity