我希望保留Kephas提供的DI抽象层,但在我的特殊情况下,我需要注册从第三方库导入的服务。因此,我不能用服务注册所需的[AppServiceContract]属性对服务进行注释。有办法做到这一点吗?
发布于 2019-03-20 21:59:48
是的有。以下是应采取的步骤:
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)));
}但是,还有第二种注册服务的方法,通过服务描述符而不是fluent 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));
}这两种情况都是自动发现的,并在适当的时候调用注册方法。但是,在第二种情况下,好处是注册可以作为稍后查询的服务元数据使用。
https://stackoverflow.com/questions/55270227
复制相似问题