同一接口的多个实现和实现在if逻辑中被调用。

问题描述 投票:0回答:1

我有一个名为ibaseinterface的接口,我用它创建了2个类,比如baseclass1和baseclass2。

现在我有一个名为顶层的类,如下图所示。

public class toplevel
{
    public ibaseinterface selection(string selection)
    {
        int.TryParse(selection, out int sel);
        if (sel < 2)
            return new baseclass1();
        else
            return new baseclass2();
    }
}

根据用户的输入,我选择需要调用的类,那么我如何解决依赖关系,在这种情况下,使用autofac。

注意:我绝对不能为基础类设置不同的接口。

design-patterns dependency-injection autofac
1个回答
0
投票

如果你需要根据一些运行时数据来选择实现,有三种典型的解决方案。

  • Proxy设计模式
  • 适配器设计模式
  • 工厂设计模式。

这是一个工厂设计模式的例子。

public interface IBaseInterfaceFactory
{
    ibaseinterface selection(string selection);
}

public class toplevel
{
    private readonly IBaseInterfaceFactory factory;
    public toplovel(IBaseInterfaceFactory factory) => this.factory = factory;

    public ibaseinterface selection(string selection)
    {
        return this.factory.selection(selection);
    }
}

// This class depends on Autofac and should therefore be placed near your Autofac registations.
internal class AutofacBaseInterfaceFactory : IBaseInterfaceFactory
{
    private readonly IComponentContext context;
    public AutofacBaseInterfaceFactory(IComponentContext context) => this.context = context;

    public ibaseinterface selection(string selection)
    {
        int.TryParse(selection, out int sel);
        if (sel < 2)
            return this.context.Resolve<baseclass1>();
        else
            return this.context.Resolve<baseclass2>();
    }
}

可以用下面的代码来连接:

builder.RegisterType<toplevel>().AsSelf();
builder.RegisterType<AutofacBaseInterfaceFactory>().As<IBaseInterfaceFactory>();
builder.RegisterType<baseclass1>().AsSelf();
builder.RegisterType<baseclass2>().AsSelf();

注意,在这种情况下 toplevel"的工作只是返回一个 IBaseInterfaceFactory,在该cae toplevel 已经充当了工厂的角色,在这种情况下,完全可以从方程中还原出来。

© www.soinside.com 2019 - 2024. All rights reserved.