有人可以帮我解决这个问题吗?
我正在尝试添加具有两个构造函数和依赖项的类 SeviceImpl 的实例。
下面是我得到的。
- 在变体 A 中,统一不会注入依赖关系。我以为会的。
在 Variant BI 中,不明白为什么 BuildUp() 方法需要在对象已经存在时检查构造函数?为什么它不能只注入依赖项?
public interface IService { void Run(); } public class Database { } public class ServiceImpl : IService { public ServiceImpl(int i) {} public ServiceImpl(bool b) { } [Dependency] public Database Db { get; set; } public void Run() {} } public static void Main() { using (var unity = new UnityContainer()) { unity.RegisterInstance<Database>(new Database()); // Now I want to register an instance of ServiceImpl // Variant A unity.RegisterInstance<IService>(new ServiceImpl(3)); var srv = unity.Resolve<IService>(); // srv.Db is null which is bad unity.BuildUp(srv); // Doesn't throw an exception // srv.Db is still null // Variant B var srv = new ServiceImpl(3); // Hoping this call will inject Database unity.BuildUp(srv); // Now it does: InvalidOperationException - The type ServiceImpl has multiple constructors of length 1. Unable to disambiguate. unity.RegisterInstance<IService>(srv); } }