如何使用Fluent API注册服务



我想保留di抽象层kepass提供的提供,但是在我的特殊情况下,我需要注册从第三方库导入的服务。鉴于此,我无法使用服务注册所需的[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)));
    }

有第二种注册服务的方法,但是通过服务描述符而不是流利的API。对于这种情况,请按照以下步骤操作:

  • 定义实现IAppServiceInfoProvider的类
  • 返回所需服务的描述符。

带有与上述相同注册的示例代码:

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));
    }

两种情况都是自动发现的,在适当的时间,调用了注册方法。但是,在第二种情况下,优势是注册可作为服务元数据可用于查询。

相关内容

  • 没有找到相关文章

最新更新