Ibr*_*tty 4 c# .net-core asp.net-core-webapi
如何实现属性和方法依赖注入?如何添加服务?最后,与使用构造函数注入相比,这能产生多大的影响?
是否可以使用属性/方法注入代替构造函数注入?
.Net 初学者,我们将不胜感激<3
在我使用构造函数 DI 的包装类中:
private ICustomerRepository _customerRepository; //For customer
private ICountryRepository _countryRepository; //For country
private IRegionRepository _regionRepository; //for region
private ICityRepository _cityRepository; //for city
// Constructor
public RepositoryWrapper(OmniConnectDB context, ICustomerRepository customerRepository, IMapper mapper, ICountryRepository countryRepository, IRegionRepository regionRepository, ICityRepository cityRepository)
{
_context = context;
_mapper = mapper;
_customerRepository = customerRepository;
_countryRepository = countryRepository;
_regionRepository = regionRepository;
_cityRepository = cityRepository;
}
Run Code Online (Sandbox Code Playgroud)
在服务方面:
// configure DI for Location Repositories
services.AddScoped<ICountryRepository, CountryRepository>();
services.AddScoped<IRegionRepository, RegionRepository>();
services.AddScoped<ICityRepository, CityRepository>();
// Configure DI for Customer Service
services.AddScoped<ICustomerService, CustomerService>();
Run Code Online (Sandbox Code Playgroud)
如ASP.NET Core 中的属性注入中所述,您无法立即获得属性注入,但您可以通过Quickwire 等扩展或完全使用不同的 DI/IoC 容器(例如Autofac)来添加它。
但:
与使用构造函数注入相比,这能产生多大的影响?
没有任何问题,但是您会遇到所有缺点:类的依赖关系不明显(您无法绕过构造函数),您可以将依赖关系保留为空,从而导致以后出现错误并妨碍编译时安全。
我遵循存储库设计模式,其中规范是创建“存储库”类。使用包装器的原因是,我不必在每个 API 中创建所有不同用户类的对象 [...] https://code-maze.com/net-core-web-development-part4 /
这是反模式的反模式。它有点像服务定位器,将实体框架提供的所有功能包装在更有限、更平等的服务中,并且具有更少的功能和更少的文档。
因此,您不必注入 anYourAppDbContext并访问其成员DbSet<Foo> Foos { get; set; },而是注入 a RepositoryWrapper(与 DbContext 相同,但可以做的更少)并获取...其Foos属性。
跳过本教程。