C# · 12月 23, 2021

c# – Unity,RegisterType <>和Singleton对象

我正在使用Unity来实例化一些对象,我发现无论我尝试什么,Unity都会为我的对象创建单例.

根据文件:
http://msdn.microsoft.com/en-us/library/dd203242.aspx#Y500

使用以下代码,我应该在每次接口解析时获得不同的实例.

IUnityContainer myContainer = new UnityContainer(); // Register a default (un-named) type mapping with a transient lifetime myContainer.RegisterType<IMyObject,MyRealObject>(); // Following code will return a new instance of MyRealObject myContainer.Resolve<IMyObject>();

但相反,我得到一个单例实例.

以下是我的声明. Global.asax中

// This should get me a singleton container.RegisterType<IRetailerService,RetailerService>(new ContainerControlledLifetimeManager(),new InjectionConstructor()); // This is the one giving me trouble.container.RegisterType<IInStoreRetailersviewmodelBuilder,InStoreRetailersviewmodelBuilder>(new InjectionConstructor(container.Resolve<IRetailerService>())); container.RegisterType<CollectController>(new InjectionConstructor(container.Resolve<IInStoreRetailersviewmodelBuilder>()));

调节器

private readonly IInStoreRetailersviewmodelBuilder _inStoreRetailersviewmodelBuilder; public CollectController(IInStoreRetailersviewmodelBuilder inStoreRetailersviewmodelBuilder) { this._inStoreRetailersviewmodelBuilder = inStoreRetailersviewmodelBuilder; } public ActionResult Index() { InStoreviewmodel viewmodel = this._inStoreRetailersviewmodelBuilder.WithRetailers().WithPostcode().Build(); }

如果我打开Chrome并运行Index操作,然后我去打开Internet Explorer并调用Index操作,在第二次调用时,在构造函数中,注入的inStoreRetailersviewmodelBuilder参数是第一次调用时生成的参数(使用Chrome) .

我已经尝试过使用PerResolveLifetimeManager()甚至来自这个线程的PerHttpRequestLifetime():MVC,EF – DataContext singleton instance Per-Web-Request in Unity

但似乎没有什么能给我一个全新的例子.任何人都可以了解我在这里做错了什么?

解决方法 试试这个,看看它是否有帮助. container.RegisterType<IInStoreRetailersviewmodelBuilder,InStoreRetailersviewmodelBuilder>(new InjectionConstructor( new ResolvedParameter<IRetailerService>())); container.RegisterType<CollectController>(new InjectionConstructor( new ResolvedParameter<IInStoreRetailersviewmodelBuilder>()));

也许通过自己将参数解析为构造函数,您实际上是在传递一个特定的实例,这导致它是一个单例.