Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何指定需要通过Autofac注册到特定类型的类型_.net_Ioc Container_Autofac - Fatal编程技术网

.net 如何指定需要通过Autofac注册到特定类型的类型

.net 如何指定需要通过Autofac注册到特定类型的类型,.net,ioc-container,autofac,.net,Ioc Container,Autofac,我想为不同的战士指定武器类型 public interface IWarrior { string Kill(); } public interface IWeapon { string KillSound(); } public class Zombie : IWarrior { private readonly IWeapon _weapon; public Zombie(IWeapon weapon) { _weapon = w

我想为不同的战士指定武器类型

public interface IWarrior
{
    string Kill();
}

public interface IWeapon
{
    string KillSound();
}

public class Zombie : IWarrior
{
    private readonly IWeapon _weapon;

    public Zombie(IWeapon weapon)
    {
        _weapon = weapon;
    }

    public string Kill()
    {
        return _weapon.KillSound();
    }
}

public class Soldier : IWarrior
{
    private readonly IWeapon _weapon;

    public Soldier(IWeapon weapon)
    {
        _weapon = weapon;
    }

    public string Kill()
    {
        return _weapon.KillSound();
    }
}

public class Gun : IWeapon
{
    public string KillSound()
    {
        return "Pif-paf";
    }
}

public class Teeth :IWeapon
{
    public string KillSound()
    {
        return "Chew-chew-chew";
    }
}
我想指定如下内容:

builder.RegisterType().As()。其中(t=>t.Name.Equals(“士兵”)
builder.RegisterType().As()。其中(t=>t.Name.Equals(“僵尸”)

我怎么能做到

我想为不同的存储库定义不同的数据库(我使用更多 不同数据类型的多个数据源)。喜欢 builder.RegisterType().As()。其中(t=>t.Name‌​.包含(“某物名称”); 和 builder.RegisterType().As()。其中(t=>t.Nam‌​e、 不。包含(“某物名”)

最好从设计中消除歧义。您的
IDbDataContext
不明确,因为
FirstDbDataContext
SecondDbDataContext
不是同一契约的真正兼容实现,因为它们不可互换;存储库需要某个数据库,当传入错误数据库的
IDbDataContext
时,存储库将失败

尝试为每个上下文提供自己的抽象,例如
IFirstDbDataContext
ISecondDbDataContext
。通过让存储库显式地依赖于这两个接口中的任何一个,查看构造函数的任何人都可以清楚地看到存储库依赖于什么

但这不仅对任何维护代码的人来说都变得容易得多,而且使用DI容器将所有内容连接在一起也变得非常容易,这仅仅是因为您消除了歧义

这是您最终将获得的注册:

builder.RegisterType<FirstDbDataContext>().As<IFirstDbDataContext>();
builder.RegisterType<SecondDbDataContext>().As<ISecondDbDataContext>();
builder.RegisterType().As();
builder.RegisterType().As();

您要做的是实际的用例吗?我发现这类示例相当有问题,因为它们不适合在实际场景中使用依赖项注入。因此,没有很好的例子来解释DI。相反,请尝试使用您试图构建的实际应用程序的概念,例如
ILoanCalculator
ICCustomerRepository
。在现实世界中,我希望为不同的存储库定义不同的DB(我为不同的数据类型使用多个数据源)。比如
builder.RegisterType().As().Where(t=>t.Name.Contains(“someName”)
builder.RegisterType().As()。其中(t=>t.Name.Not.Contains(“someName”)