Pregunta

I want to specify type of weapon for different warriors

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";
    }
}

I want to specify something like this:

builder.RegisterType<Gun>().As<IWeapon>().Where(t => t.Name.Equals("Soldier")); builder.RegisterType<Teeth>().As<IWeapon>().Where(t => t.Name.Equals("Zombie"));

How I can do this?

¿Fue útil?

Solución

I want to define different DB for different repositories (I use more than one datasources for different datatypes). Like builder.RegisterType().As().Where(t=>t.Name‌​.Contains("someName")); and builder.RegisterType().As().Where(t=>t.Nam‌​e.Not.Contains("someName"));

It might be better to remove the ambiguity from your design. Your IDbDataContext is ambiguous, since FirstDbDataContext and SecondDbDataContext are not really compatible implementations of the same contract, since they aren't interchangeable; a repository requires a certain database and it will fail when an IDbDataContext for the wrong database is passed in.

Try giving each context its own abstraction, such as IFirstDbDataContext and ISecondDbDataContext. By letting a repository depend explicitly on either of those interfaces it becomes clear to anyone who looks at the constructor what this repository depends on.

But it not only becomes much easier for anyone maintaining the code, it becomes significantly easier to wire everything together using a DI container, simply because you removed the ambiguity.

This is the registration you'll end up with:

builder.RegisterType<FirstDbDataContext>().As<IFirstDbDataContext>();
builder.RegisterType<SecondDbDataContext>().As<ISecondDbDataContext>();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top