1

It appears that Unity IoC defaults to creating a new instance of an object when it resolves a type. But my question is there someway to be explicit and tell my container that whenever I have it resolve an object type to give me a new instance of said type?

IE i want to be explicit and force the container to make sure theInstance is a new instance each time it resolves type:MyNewObject (or all types for that matter)

MyNewObject theInstance = container.Resolve<MyNewObject>();
4

2 回答 2

2

是的,它可以通过TransientLifetimeManager轻松配置

当你注册一个类时应该有类似的东西

container.Register<IMyNewObject, MyMewObject>(new TransientLifetimeManager());
//or
container.Register<MyMewObject>(new TransientLifetimeManager())
于 2012-08-19T17:53:09.300 回答
0

如果您正确应用 IoC 原则,您的类会声明其依赖项,然后容器会处理它们的生命周期。例如,您想获取一个 HttpRequest 对象,并且容器句柄提供当前线程本地对象,或者其他。

你的代码不应该真正关心它的依赖的生命周期,因为它不应该负责清理它们或你有什么(所有这些都应该封装在依赖本身中,并由容器关闭时)。

但是,如果您确实需要在代码中关心是否获得了单例实例或相同类型的每个注入实例,我喜欢通过使用类型系统本身来明确它,就像 Java 的 Guice 容器一样它的Provider模式。我创建了一个 Guice 风格的IProvider<T>界面,我用它来做这件事,我只是用一个简单的静态工厂方法为它们连接起来,如下所示:

Provider.Of<Foo>(() => { /* Code to return a Foo goes here */})
于 2012-08-19T18:00:04.507 回答