在 IoC 容器中一次性注入 class
Disposable of injected class in IoC container
我有Parent
class和一个Child
class,
parent 对 child 做了一些处理,然后处理掉它。
class Parent
{
private IChild _child;
Parent(IChild child) { this._child=child }
DoAndDisposeChild()
{
//code
//this._child.dispose();
}
}
使用 autofac
,我正在解析 Parent
并调用 DoAndDisposeChild
方法:
container.Resolve<Parent>().DoAndDisposeChild().
我通过使用 autofac
的 Owend
功能成功地实现了这一目标:
private Owned<IChild> _child;
并将DoAndDisposeChild
修改为:
DoAndDisposeChild()
{
//code
this._child.Dispose();
}
问题是我正在将我的代码耦合到 autofac
,我正在寻找使用 autofac
而不 来实现处理问题的方法?
要将业务逻辑与 Autofac 分离,需要将 Child-class 注册为在 Composition Root[=26 上具有 external ownership =]-级别。在这种情况下,Autofac 不会担心处理 any 实例 Child:
builder
.RegisterType<Child>()
.As<IChild>
.ExternallyOwned();
传递给构造函数IChild:
class Parent
{
private IChild _child;
public Parent(IChild child) { this._child=child }
// ..
}
作为替代方法,子实例的创建可以通过工厂或 something else:
等单独的服务收费
class Parent
{
private IChild _child;
public Parent(IChildFactory childFactory) { this._child = childFactory.CreateChild(); }
}
我有Parent
class和一个Child
class,
parent 对 child 做了一些处理,然后处理掉它。
class Parent
{
private IChild _child;
Parent(IChild child) { this._child=child }
DoAndDisposeChild()
{
//code
//this._child.dispose();
}
}
使用 autofac
,我正在解析 Parent
并调用 DoAndDisposeChild
方法:
container.Resolve<Parent>().DoAndDisposeChild().
我通过使用 autofac
的 Owend
功能成功地实现了这一目标:
private Owned<IChild> _child;
并将DoAndDisposeChild
修改为:
DoAndDisposeChild()
{
//code
this._child.Dispose();
}
问题是我正在将我的代码耦合到 autofac
,我正在寻找使用 autofac
而不 来实现处理问题的方法?
要将业务逻辑与 Autofac 分离,需要将 Child-class 注册为在 Composition Root[=26 上具有 external ownership =]-级别。在这种情况下,Autofac 不会担心处理 any 实例 Child:
builder
.RegisterType<Child>()
.As<IChild>
.ExternallyOwned();
传递给构造函数IChild:
class Parent
{
private IChild _child;
public Parent(IChild child) { this._child=child }
// ..
}
作为替代方法,子实例的创建可以通过工厂或 something else:
等单独的服务收费class Parent
{
private IChild _child;
public Parent(IChildFactory childFactory) { this._child = childFactory.CreateChild(); }
}