使用autofac

时间:2018-10-25 12:48:12

标签: c# autofac

使用下面的PipelineX类,无需注入autofac容器并调用_container.Resolve(),就有任何方法可以解决应用于pipline的过滤器。

 public class PipelineX<T> : FilterBase<T>, IPipelineX<T>
{
    private readonly IContainer _container;

    public PipelineX(IContainer container)
    {
        _container = container;
    }
    protected override T Process(T input)
    {
        return input;
    }

    public PipelineX<T> FilterBy<X>()
    {
        var filter = _container.Resolve(typeof(X)) as IFilter<T>;
        Register(filter);
        return this;
    }                             
}

2 个答案:

答案 0 :(得分:4)

要避免将Autofac用作服务定位器,您可以在其中注册您自己的工厂方法,在这种情况下:

builder.Register<Func<Type, object>>((c, p) =>
{
    var context = c.Resolve<IComponentContext>();
    return type => context.Resolve(type);
});

并像下面这样在您的PipelineX类中使用它:

private readonly Func<Type, object> filterFactory;

public PipelineX(Func<Type, object> filterFactory)
{
    this.filterFactory = filterFactory;
}

protected override T Process(T input)
{
    return input;
}

public PipelineX<T> FilterBy<X>()
{
    var filter = this.filterFactory(typeof(X)) as IFilter<T>;
    Register(filter);
    return this;
}

考虑因素::这仅删除对Autofac容器的硬引用,它仍使用抽象对象工厂,该工厂本身不足以说明自我,应由自定义过滤器工厂或选择器实现代替。 / p>

答案 1 :(得分:2)

这与Péter的答案类似,但使用的是自定义工厂:

public class FilterFactory
{
    private readonly Func<Type, object> _factoryFunc;

    public FilterFactory(Func<Type, object> factoryFunc)
    {
        _factoryFunc = factoryFunc ?? throw new ArgumentNullException(nameof(factoryFunc));
    }

    public IFilter<T> Create<X, T>() 
    {
        IFilter<T> filter = Create<T>(typeof(X));

        return filter;
    }

    public IFilter<T> Create<T>(Type type) 
    {
        var filter = _factoryFunc(type) as IFilter<T>;

        if (filter == null)
        {
            throw new ArgumentException($"Could not find filter for type '{type.FullName}'");
        }

        return filter;
    }
}

PipelineX实现为:

public class PipelineX<T> : FilterBase<T>, IPipelineX<T>
{
    private readonly FilterFactory _factory;

    public PipelineX(FilterFactory factory)
    {
        _factory = factory;
    }

    protected override T Process(T input)
    {
        return input;
    }

    public PipelineX<T> FilterBy<X>()
    {
        var filter = _factory.Create<X,T>() as IFilter<T>;
        Register(filter);
        return this;
    }
}

使用Autofac注册工厂:

builder.Register<FilterFactory>(c =>
{
    var context = c.Resolve<IComponentContext>();
    return new FilterFactory(context.Resolve);
});