摆脱静态类中的依赖

时间:2014-07-29 14:40:10

标签: c# dependency-injection autofac

我需要重构一个项目才能使用Autofac。但我正努力尝试在具有这样的构造函数的服务(CrmCustomerService)中使用它:

//...

private readonly CrmService _service;

//...

public CrmCustomerService()
{
    _service = InstantiateCrmIntegrationWebServices();
}

public static CrmService InstantiateCrmIntegrationWebServices()
{
    var service = new CrmService();
    if (!string.IsNullOrEmpty(ConfigParameter.GetS("webservices.url.CrmIntegrationWebService")))
    {
        service.Url = ConfigParameter.GetS("webservices.url.CrmIntegrationWebService");
    }

    var token = new CrmAuthenticationToken
    {
        AuthenticationType = 0, 
        OrganizationName = "Foo"
    };
    service.CrmAuthenticationTokenValue = token;
    service.Credentials = new NetworkCredential(ConfigParameter.GetS("crm.UserId"), ConfigParameter.GetS("crm.Password"), ConfigParameter.GetS("crm.Domain"));
    return service;
}

我怎样才能在CrmCustomerService构造函数中注入CrmService?如果我能够告诉Autofac将此方法用于该依赖但不确定我是否能够实现这一点,那就足够了。

由于

1 个答案:

答案 0 :(得分:0)

Autofac can accept a delegate or lambda expression to be used as a component creator。这将允许您在CrmService服务的注册中将CrmService的创建封装在lambda表达式中。

使用以下缩减CrmService类型和关联的提取界面:

public interface ICrmService
{
    string Url { get; set; }
}

public class CrmService : ICrmService
{
    public string Url { get; set; }
}

然后在构建器配置中注册ICrmService服务,如下所示:

builder.Register<ICrmService>(x =>
{
    var service = new CrmService
    {
        Url = "Get url from config"               
    };
    return service;
});

然后照常注入CrmCustomerService类型。

<强>更新 或者,如果您不想为CrmService提取界面,请执行以下操作:

builder.Register<CrmService>(x =>
{
    var service = new CrmService
    {
        Url = "Get url from config"               
    };
    return service;
});