我尝试注册基于泛型类的具体类,而这个泛型类是基于泛型接口(interface)的。问题是如何在 CaSTLe Windsor 和 ASP.NET Boilerplate 中执行此操作,这样我就不需要很多代码来一一注册它。
public interface IService<T> where T: class ...
public class Service<T, TE, TPrimary> : IService<T> where T: class ...
public class ConcreteService : Service<SomeType, SomeType2, string> ...
public class AnotherConcreteService : Service<AnotherSomeType, AnotherSomeType2, string> ...
有了这样的结构,我想注册到IService<SomeType>
类(class)ConcreteService
,它实现了这个服务。我怎么能用温莎城堡做到这一点?一个一个的实现看起来像这样:
IocManager.IocContainer.Register(Component.For(typeof(IQueryService<SomeType>))
.ImplementedBy(typeof(ConcreteService)).Named("ConcreteTest"));
IocManager.IocContainer.Register(Component.For(typeof(IQueryService<AnotherSomeType>))
.ImplementedBy(typeof(AnotherConcreteService)).Named("AnotherConcreteTest"));
我想要的用法:
var test1 = IocContainer.Resolve<IQueryService<SomeType>(); // Here should be ConcreteService
var test2 = IocContainer.Resolve<IQueryService<AnotherSomeType>(); // Here should be AnotherConcreteService
通过逐行方法,它可以工作,但如何根据 IQueryService<>
注册所有内容?
最佳答案
1。 IQueryService<SomeTypeDto>
Castle.MicroKernel.ComponentNotFoundException: No component for supporting the service AbpCompanyName.AbpProjectName.IGenerics.IQueryService`1[[AbpCompanyName.AbpProjectName.SomeEntitiesDto.SomeTypeDto, AbpCompanyName.AbpProjectName.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] was found
要将具体类注册到通用接口(interface),请使用 .WithService.Base()
.
与RegisterAssemblyByConvention
的兼容性1 , 配置唯一名称。
public override void Initialize()
{
var thisAssembly = ...
IocManager.RegisterAssemblyByConvention(thisAssembly);
IocManager.IocContainer.Register(
Classes.FromAssembly(thisAssembly)
.BasedOn(typeof(IQueryService<>))
.WithService.Base()
.Configure(configurer => configurer.Named(Guid.NewGuid().ToString())) // Add this
);
// ...
}
1 如果您的具体类实现了 ASP.NET Boilerplate 的 ITransientDependency
, 然后使用默认名称为 .WithService.Self()
注册类里面RegisterAssemblyByConvention
.
2。 IRepository<SomeType>
Castle.MicroKernel.Handlers.HandlerException: Can't create component 'AbpCompanyName.AbpProjectName.SomeEntityService.SomeTypeService' as it has dependencies to be satisfied.
'AbpCompanyName.AbpProjectName.SomeEntityService.SomeTypeService' is waiting for the following dependencies:
- Service 'Abp.Domain.Repositories.IRepository`1[[AbpCompanyName.AbpProjectName.SomeEntities.SomeType, AbpCompanyName.AbpProjectName.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' which was not registered.
要使用 ASP.NET Boilerplate 存储库,请定义一个public DbSet。
public class AbpProjectNameDbContext : ...
{
/* Define a DbSet for each entity of the application */
// DbSet<SomeType> SomeEntities { get; set; } // Remove this
public DbSet<SomeType> SomeEntities { get; set; } // Add this
// ...
}
关于c# - 如何将具体类注册到通用接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56825208/