Specify constructor for the Unity IoC container to use

北城以北 提交于 2019-11-28 22:23:30

Register it like this instead:

container.RegisterType<Person>(new InjectionConstructor());

You can add the LifetimeManager as well using an overload of the RegisterType method.

That said, when modeling for DI, your life will be much easier if you have unambiguous contructors (i.e. no overloaded constructors).

By default, Unity chooses a constructor with maximum number of arguments. To override this, decorate required constructor with InjectionConstructorAttribute.

Multiple-Constructor Injection Using an Attribute

When a target class contains more than one constructor with the same number of parameters, you must apply the InjectionConstructor attribute to the constructor that the Unity container will use to indicate which constructor the container should use. As with automatic constructor injection, you can specify the constructor parameters as a concrete type, or you can specify an interface or base class for which the Unity container contains a registered mapping.

I really have to point out the way you're using dependency injection in this instance is just wrong. The container should be able to inject SomeValueObject on the construction.

What you most likely should do is register a default object of SomeValueObject that the .Name property returns string.Empty instead.

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