【问题标题】:Autofac and Generic Typed Factory like Castle WindsorAutofac 和 Generic Typed Factory,如 Castle Windsor
【发布时间】:2017-12-13 09:29:11
【问题描述】:

在当前项目中,我正在使用 Autofac,但通常我使用 Castle Windsor,因此我试图了解如何解决 类型化工厂 模式在 Castle Windsor 中可用,使用 Autofac。

我有以下查询和查询处理程序合同:

public interface IQuery<out TResult>
{

}

public interface IQueryHandler<in TQuery, out TResult> where TQuery : IQuery<TResult>
{
    TResult Handle(TQuery query);
}

每个合约都有多个实现,因此每个IQuery&lt;result&gt; 都有一个对应的IQueryHandler&lt;IQuery&lt;result&gt;, result&gt; 实现。

我正在使用这种流畅的方法注册所有内容:

public class CqrsModule : Module
{
    /// <inheritdoc />
    protected override void Load(ContainerBuilder builder)
    {
        // prepare all assemblies for IoC
        var assemblies = new[]
        {
            typeof(IQuery<>).Assembly,
            typeof(IQueryHandler<,>).Assembly,
            typeof(IBus).Assembly
        };

        // autofac regisration
        builder.RegisterAssemblyTypes(assemblies)
            .AsClosedTypesOf(typeof(IQuery<>))
            .AsClosedTypesOf(typeof(IQueryHandler<,>))
            .AsClosedTypesOf(typeof(IBus));
    }
}

但是我有一个问题。在我的总线上,我不想知道现有的处理程序,所以我使用 Typed Factory,如下所示:

public interface IQueryFactory
{
    IQueryHandler<TQuery, TResult> BuildHandler<TQuery, TResult>() 
    where TQuery : IQuery<TResult>;
}

但我不知道如何使用 Autofac 注册这个 Typed Factory。在温莎城堡我会做:

kernel.Register(
    Component.For<IQueryFactory>()
        .AsFactory()
);

【问题讨论】:

    标签: c# autofac typed-factory-facility


    【解决方案1】:

    显然答案是否定的,因为Autofac没有Typed Factory这样的概念。

    另一种方法是保留合同并为特定情况创建一个实现,即在 Autofac 中使用类型化工厂

    public sealed class AutofacQueryFactory : IQueryFactory
    {
        private readonly ILifetimeScope scope;
    
        public AutofacQueryFactory(ILifetimeScope scope)
        {
            this.scope = scope;
        }
    
        /// <see cref="IQueryFactory" />
        public IQueryHandler<TQuery, TResult> BuildHandler<TQuery, TResult>() where TQuery : IQuery<TResult>
        {
            return this.scope.Resolve<IQueryHandler<TQuery, TResult>>();
        }
    }
    

    注意 根据 Autofac 文档,您应该注入 ILifetimeScope 而不是 IContainer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      相关资源
      最近更新 更多