我需要重构一个项目才能使用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将此方法用于该依赖但不确定我是否能够实现这一点,那就足够了。
由于
答案 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;
});