C# 摆脱静态类中的依赖关系
为了使用Autofac,我需要重构一个项目。但我正在努力尝试在一个具有如下构造函数的服务(CrmCustomerService)中使用它:C# 摆脱静态类中的依赖关系,c#,dependency-injection,autofac,C#,Dependency Injection,Autofac,为了使用Autofac,我需要重构一个项目。但我正在努力尝试在一个具有如下构造函数的服务(CrmCustomerService)中使用它: //... private readonly CrmService _service; //... public CrmCustomerService() { _service = InstantiateCrmIntegrationWebServices(); } public static CrmService InstantiateCrm
//...
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;
}
如何将CrmService注入到CrmCustomerService构造函数中?如果我能告诉Autofac使用这种方法来处理依赖关系,但不确定我是否能做到这一点,那就足够了
谢谢。这将允许您在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;
});
感谢@LongboatHarry,如果我无法在CrmService上创建接口,是否可以使用AsSelf()绑定它?当然可以-可以告诉AutoFac根据具体的服务进行解析。请参阅更新。
builder.Register<CrmService>(x =>
{
var service = new CrmService
{
Url = "Get url from config"
};
return service;
});