Dependency injection 如何使用fluent API在Kephas中注册服务?
我想保留Kephas提供的DI抽象层,但在我的特殊情况下,我需要注册一个从第三方库导入的服务。鉴于此,我无法使用服务注册所需的Dependency injection 如何使用fluent API在Kephas中注册服务?,dependency-injection,kephas,Dependency Injection,Kephas,我想保留Kephas提供的DI抽象层,但在我的特殊情况下,我需要注册一个从第三方库导入的服务。鉴于此,我无法使用服务注册所需的[AppServiceContract]属性对服务进行注释。有没有办法做到这一点?有。以下是要遵循的步骤: 定义一个实现IConventionsRegistrar的类 使用约定生成器注册所需的服务 示例代码: public class MyConventionsRegistrar : IConventionsRegistrar { /// <summar
[AppServiceContract]
属性对服务进行注释。有没有办法做到这一点?有。以下是要遵循的步骤:
- 定义一个实现
的类IConventionsRegistrar
- 使用约定生成器注册所需的服务
public class MyConventionsRegistrar : IConventionsRegistrar
{
/// <summary>
/// Registers the conventions.
/// </summary>
/// <param name="builder">The registration builder.</param>
/// <param name="candidateTypes">The candidate types which can take part in the composition.</param>
/// <param name="registrationContext">Context for the registration.</param>
public void RegisterConventions(
IConventionsBuilder builder,
IEnumerable<TypeInfo> candidateTypes,
ICompositionRegistrationContext registrationContext)
{
//... here you can use the conventions builder to register your services using the fluent API. The candidate types are provided if you need the identified application types. A couple of examples are provided below:
// shared/singleton service exported as IMyService with MyService implementation.
builder.ForType(typeof(MyServiceImpl))
.Export(b => b.AsContractType(typeof(IMyService)))
.Shared();
// instance-based multiple services exported as IMultiImplService
builder.ForTypesDerivedFrom(typeof(IMultiImplService))
.Export(b => b.AsContractType(typeof(IMultiImplService)));
}
这两种情况都是自动发现的,并在适当的时候调用注册方法。然而,在第二种情况下,优势在于注册可以作为服务元数据在以后查询
public class MyAppServiceInfoProvider : IAppServiceInfoProvider
{
/// <summary>
/// Gets an enumeration of application service information objects.
/// </summary>
/// <param name="candidateTypes">The candidate types which can take part in the composition.</param>
/// <param name="registrationContext">Context for the registration.</param>
/// <returns>
/// An enumeration of application service information objects and their associated contract type.
/// </returns>
public IEnumerable<(TypeInfo contractType, IAppServiceInfo appServiceInfo)> GetAppServiceInfos(IEnumerable<TypeInfo> candidateTypes, ICompositionRegistrationContext registrationContext)
{
yield return (typeof(IMyService).GetTypeInfo(),
new AppServiceInfo(typeof(IMyService),
typeof(MyServiceImpl),
AppServiceLifetime.Shared));
yield return (typeof(IMultiImplService).GetTypeInfo(),
new AppServiceInfo(typeof(IMultiImplService),
AppServiceLifetime.Instance,
allowMultiple: true));
}