我试图通过使用Unity将基于接口的两个对象注入到类构造函数中.
单元测试时我当前收到以下错误:
Result Message:
Test method TestProject.TFStests.Check_Interface_CheckOut_Method threw exception:
System.InvalidOperationException: The type Adp.Tools.VersionControl.TfsVersionControl.TfsVcPromotionManager does not have a constructor that takes the parameters (TfsVcQaCheckoutWorker).
以下代码是我的Unity类,用于注册和解析TfsVCPromotionManager对象:
public class UnityClass { public static ITfsVcPromotionManager returnNewPromotionManager( VersionControlServer tfServer) { var container = new UnityContainer(); ITfsVcQaCheckinWorker test1 = CreateUnityCheckInWorker(); ITfsVcQaCheckoutWorker test2 = CreateUnityCheckOutWorker(tfServer); container.RegisterType<ITfsVcPromotionManager,TfsVcPromotionManager>( new InjectionConstructor(test2),new InjectionConstructor(test1)); return container.Resolve<TfsVcPromotionManager>(); } private static ITfsVcQaCheckinWorker CreateUnityCheckInWorker() { var container = new UnityContainer(); container.RegisterType<ITfsVcQaCheckinWorker,ITfsVcQaCheckinWorker>(); return container.Resolve<TfsVcQaCheckinWorker>(); } private static ITfsVcQaCheckoutWorker CreateUnityCheckOutWorker( VersionControlServer passedServer) { var container = new UnityContainer(); container.RegisterType<ITfsVcQaCheckoutWorker,TfsVcQaCheckoutWorker>( new InjectionConstructor(passedServer)); return container.Resolve<TfsVcQaCheckoutWorker>(); } }
这是TfsVcPromotionManager类的构造函数.请注意,它明确地接受了基于ITfsVcQaCheckoutworker和ITfsVcCheckinWorker接口的实例.
private ITfsVcQaCheckoutWorker _checkOutWorker; private ITfsVcQaCheckinWorker _checkInWorker; public TfsVcPromotionManager(ITfsVcQaCheckoutWorker checkOutWorker,ITfsVcQaCheckinWorker checkInWorker) { if (checkOutWorker == null || checkInWorker == null) { throw new NullReferenceException(); } _checkOutWorker = checkOutWorker; _checkInWorker = checkInWorker; }
任何人都可以告诉我我做错了什么.
解决方法
它说它找不到“带参数的构造函数(TfsVcQaCheckoutWorker)”,这确实是一个真实的陈述.没有构造函数只接受一个参数.我对Unity并不熟悉,但我打赌你的问题可以通过改变这个来解决:
container.RegisterType<ITfsVcPromotionManager,TfsVcPromotionManager>( new InjectionConstructor(test2),new InjectionConstructor(test1))
对此:
container.RegisterType<ITfsVcPromotionManager,TfsVcPromotionManager>( new InjectionConstructor(test2,test1))
有关InjectionConstructor的constructor,请参阅MSDN参考.