【问题标题】:How to specify some parameters using WithParameter method and let autofac resolve unspecifed parameters如何使用 WithParameter 方法指定一些参数并让 autofac 解析未指定的参数
【发布时间】:2015-04-29 07:33:43
【问题描述】:

我有一个类在构造函数中接收接口和字符串参数:

public MyClass(IService service, string config) : IMyClass

在Autofac中,接口被注册:

builder.RegisterType<Service>()
       .As<IService>()
       .InstancePerRequest();

MyClass 也注册了WithParameter 方法用于字符串参数:

builder.RegisterType<MyClass>()
       .As<IMyClass>()
       .WithParameter("config", parameters["Config"]);

但是如何将IService接口已经解析的对象传递给MyClass构造函数呢?

我原以为上面使用IService注册就够了,但是当使用WithParameter方法时,我显然需要以同样的方式声明所有参数。

【问题讨论】:

    标签: c# autofac


    【解决方案1】:

    我期待上面使用的 IService 注册是 够了

    你的假设是正确的。

    在使用WithParameter方法的时候,我显然需要声明所有 参数方式相同。

    您不需要将service 参数与config 参数一起传递。容器会为你解决。

    下面两行就够了——

    builder.RegisterType<Service>().As<IService>().InstancePerRequest();
    
    builder.RegisterType<MyClass>().As<IMyClass>()
       .WithParameter("config", parameters["Config"]).InstancePerRequest();
    

    【讨论】:

    • 够了吗?因为当我从构造函数中删除 IService 时,它​​可以正常解决。但是当我把它放回去时,我得到“尝试创建'UsersController'类型的控制器时发生错误。确保控制器具有无参数的公共构造函数”,这意味着无法解析MyClass。
    • 应该够了。看看这个样本:dotnetfiddle.net/x0xBcn。顺便说一句,错误消息不会查看 Autofac 消息。你是否配置了 ASP.net MVC 的 DependencyResolver(例子见docs.autofac.org/en/latest/integration/mvc.html#quick-start
    猜你喜欢
    • 1970-01-01
    • 2019-09-02
    • 2018-08-29
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多