我不确定我问这个问题是否正确,所以请耐心等待,因为这对我来说都是新的。
我试图完全掌握 .NET Core 中的依赖注入,同时也试图理解正确的设计模式。我找到了一个很棒的教程(老师很优秀,解释得很好),但问题是教程中的示例应用程序是使用 Visual Studio 2010 使用 Unity 进行依赖注入构建的。
我正在尝试将 DI 转换为 VS 2022 中的应用程序,但我不明白如何在 .NET Core 的服务部分中包含方法的注入。
使用 Unity 的示例如下所示:
public static ICustomer Create(string TypeCust)
{
if (custs == null)
{
custs = new UnityContainer();
custs.RegisterType<ICustomer,Customer>("Customer", new InjectionConstructor(new CustomerValidationAll()));
custs.RegisterType<ICustomer, Lead.("Lead", new InjectionConstructor(new LeadValidation()));
}
return custs.Resolve<ICustomer>(TypeCust);
}
我知道如何在 .NET Core 中包含接口和具体类:
services.AddScoped<ICustomer, Customer>();
services.AddScoped<ICustomer, Lead>();
根据要求,这是其余的代码:
public interface ICustomer
{
string CustomerName { get; set; }
string PhoneNumber { get; set; }
decimal BillAmount { get; set; }
public DateTime BillDate { get; set; }
string Address { get; set; }
void Validation();
}
public interface IValidation<Any>
{
void Validate(Any obj);
}
public class CustomerValidationAll : IValidation<ICustomer>
{
public void Validate(ICustomer obj)
{
if (obj.CustomerName?.Length == 0)
{
throw new Exception("Customer Name is required");
}
if (obj.PhoneNumber?.Length == 0)
{
throw new Exception("Phone Number is required");
}
if (obj.BillAmount == 0)
{
throw new Exception("Bill Amount is required");
}
if (obj.BillDate >= DateTime.Now)
{
throw new Exception("Bill date is incorrect");
}
if (obj.Address?.Length == 0)
{
throw new Exception("Address is required");
}
}
}
public class LeadValidation : IValidation<ICustomer>
{
public void Validate(ICustomer obj)
{
if (obj.CustomerName?.Length == 0)
{
throw new Exception("Customer Name is required");
}
if (obj.PhoneNumber?.Length == 0)
{
throw new Exception("Phone Number is required");
}
}
}
我不知道如何包含上述示例中
CustomerValidationAll()
中的验证方法 LeadValidation()
和 InjectionContstructor
。
有人可以帮助我吗?
这里有一些方法可以实现这一点,基本上,您可以创建一个 ServiceResolver 或一个工厂来使用密钥检索对象,或者使用反模式。
您可以在此处查看更多信息:https://andrewlock.net/exploring-the-dotnet-8-preview-keyed-services-dependency-injection-support/