4

我有以下课程:

public class Errors
{ 
    private readonly string _connectionString;
    public Errors(string connectionString)
    {
         _connectionString = connectionString;
    }
}

我正在尝试像这样使用 Autofac 进行注册:

builder.RegisterType<Errors>().WithParameter("connectionString", System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString);

该对象被注入到另一个对象中,但它始终为空。进一步查看异常,显示以下错误消息:

Cannot choose between multiple constructors with equal length 1 on type   'System.String'.
Select the constructor explicitly, with the UsingConstructor() configuration method, when the component is registered.

我尝试使用 UsingConstructor 和 WithParameter 进行注册,但没有任何变化。

4

1 回答 1

4

试试这个,有两种注册方式

第一种

builder.Register(c => new Errors(System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString)).InstancePerLifetimeScope();

第二种

public class Errors
{ 
    private string _connectionString{ get; set; }

    public Errors(string connectionString)
    {
        _connectionString = connectionString;
    }
}

注册如下

builder.RegisterType<Errors>().WithParameter("connectionString", System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString);

编辑:测试

class Program
{
    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();
        builder.Register(c => new Errors(ConfigurationManager.ConnectionStrings["myConn"].ConnectionString)).InstancePerLifetimeScope();      // Type 1
        // builder.RegisterType<Errors>().WithParameter("connectionString", ConfigurationManager.ConnectionStrings["myConn"].ConnectionString); // Type 2
        var container = builder.Build();

        var objErrors = container.Resolve<Errors>();
    }
}

配置文件看起来像

  <connectionStrings>
     <add name="myConn" connectionString="Some Connection String"/>
  </connectionStrings>

请阅读此 Autofac Wiki

在 Autofac 版本中测试:2.6.1.841

结果结果

于 2012-11-06T18:40:33.677 回答