简体   繁体   English

配置autofac容器

[英]Configuring the autofac container

How to configure a DI Container in a difficult situation? 在困难情况下如何配置DI容器?

There are 3 entities 有3个实体

class First: IFirst
public First (ISecond second)
{}
class Second : ISecond
public Second (IThird third, IOther other)
{}

Need to create the First. 需要创造第一。 But at the same time: 但同时:

  1. IThird must be created by Autofac according to the rules configuration. 必须由Autofac根据规则配置创建IThird。
  2. IOther must be given by me 我必须给我其他

I thought it would work: 我认为这会起作用:

auto.RegisterType<First>()
.WithParameter("second", new Second (auto.Resolve<IThird>(), new MyOther(myValue)))

But there is no method ContainerBuilder Resolve ! 但是没有方法ContainerBuilder解决!

How this can be done? 如何做到这一点?

You can't resolve service using a ContainerBuilder but you can use another overload with a delegate parameter that will give you access to the container. 您不能使用ContainerBuilder解析服务,但是可以使用另一个带有委托参数的重载,该重载将使您能够访问容器。

cb.RegisterType<First>()
  .WithParameter((pi, c) => pi.Name == "second", 
                 (pi, c) => new Second(c.Resolve<IThird>(), new MyOther(myValue)));

or 要么

cb.RegisterType<First>()
  .WithParameter((pi, c) => pi.Name == "second", 
                 (pi, c) => c.Resolve<ISecond>(TypedParameter.From<MyOther>(myValue)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM