配置 autofac 容器
Configuring the autofac container
如何在困难的情况下配置 DI Container?
有 3 个实体
class First: IFirst
public First (ISecond second)
{}
class Second : ISecond
public Second (IThird third, IOther other)
{}
需要创建第一个。但同时:
- ITird必须由Autofac根据规则配置创建。
- 其他必须由我给
我认为它会起作用:
auto.RegisterType<First>()
.WithParameter("second", new Second (auto.Resolve<IThird>(), new MyOther(myValue)))
但是没有 ContainerBuilder Resolve 方法!
如何做到这一点?
您无法使用 ContainerBuilder
解析服务,但您可以使用另一个带有委托参数的重载,这样您就可以访问容器。
cb.RegisterType<First>()
.WithParameter((pi, c) => pi.Name == "second",
(pi, c) => new Second(c.Resolve<IThird>(), new MyOther(myValue)));
或
cb.RegisterType<First>()
.WithParameter((pi, c) => pi.Name == "second",
(pi, c) => c.Resolve<ISecond>(TypedParameter.From<MyOther>(myValue)));
如何在困难的情况下配置 DI Container?
有 3 个实体
class First: IFirst
public First (ISecond second)
{}
class Second : ISecond
public Second (IThird third, IOther other)
{}
需要创建第一个。但同时:
- ITird必须由Autofac根据规则配置创建。
- 其他必须由我给
我认为它会起作用:
auto.RegisterType<First>()
.WithParameter("second", new Second (auto.Resolve<IThird>(), new MyOther(myValue)))
但是没有 ContainerBuilder Resolve 方法!
如何做到这一点?
您无法使用 ContainerBuilder
解析服务,但您可以使用另一个带有委托参数的重载,这样您就可以访问容器。
cb.RegisterType<First>()
.WithParameter((pi, c) => pi.Name == "second",
(pi, c) => new Second(c.Resolve<IThird>(), new MyOther(myValue)));
或
cb.RegisterType<First>()
.WithParameter((pi, c) => pi.Name == "second",
(pi, c) => c.Resolve<ISecond>(TypedParameter.From<MyOther>(myValue)));