2

是否可以为所有它实现的接口注册一个类型?例如,我有一个:

public class Bow : IWeapon
{

    #region IWeapon Members

    public string Attack()
    {
        return "Shooted with a bow";
    }

    #endregion
}

public class HumanFighter 

{
    private readonly IWeapon weapon = null;
    public HumanFighter(IWeapon weapon)
    {
        this.weapon = weapon;
    }

    public string Fight()
    {

        return this.weapon.Attack();
    }

}

    [Test]
    public void Test2b()
    {
        Container container = new Container();
        container.RegisterSingle<Bow>();
        container.RegisterSingle<HumanFighter>();

        // this would match the IWeapon to the Bow, as it
        // is implemented by Bow
        var humanFighter1 = container.GetInstance<HumanFighter>(); 

        string s = humanFighter1.Fight();
    }
4

1 回答 1

1

这完全取决于您的需要,但通常您需要使用Container的非通用注册方法。您可以定义自己的 LINQ 查询来查询应用程序的元数据以获取正确的类型,并使用非泛型注册方法注册它们。这是一个例子:

var weaponsAssembly = typeof(Bow).Assembly;

var registrations =
    from type in weaponsAssembly.GetExportedTypes()
    where type.Namespace.Contains(".Weapons")
    from service in type.GetInterfaces()
    select new { Service = service, Implementation = type };

foreach (var reg in registrations)
{
    container.Register(reg.Service, reg.Implementation);
}

如果您需要批量注册一组实现,基于共享的通用接口,您可以使用RegisterManyForOpenGeneric扩展方法:

// include the SimpleInjector.Extensions namespace.

container.RegisterManyForOpenGeneric(typeof(IValidator<>),
    typeof(IValidator<>).Assembly);

这将在提供的程序集中查找所有(非泛型)公共类型,这些公共类型IValidator<T>通过它们的封闭泛型实现实现并注册它们中的每一个。如果一个类型实现了 的多个封闭泛型版本IValidator<T>,则所有版本都将被注册。看看下面的例子:

interface IValidator<T> { }
class MultiVal1 : IValidator<Customer>, IValidator<Order> { }
class MultiVal2 : IValidator<User>, IValidator<Employee> { }

container.RegisterManyForOpenGeneric(typeof(IValidator<>),
    typeof(IValidator<>).Assembly);

假设给定的接口和类定义,显示的RegisterManyForOpenGeneric注册等效于以下手动注册:

container.Register<IValidator<Customer>, MultiVal1>();
container.Register<IValidator<Order>, MultiVal1>();
container.Register<IValidator<User>, MultiVal2>();
container.Register<IValidator<Employee>, MultiVal2>();

添加方便的扩展方法也很容易。以下面的扩展方法为例,它允许您通过其所有实现的接口注册单个实现:

public static void RegisterAsImplementedInterfaces<TImpl>(
    this Container container)
{
    foreach (var service in typeof(TImpl).GetInterfaces())
    {
        container.Register(service, typeof(TImpl));
    }
}

它可以按如下方式使用:

container.RegisterAsImplementedInterfaces<Sword>();
于 2012-10-18T16:58:46.623 回答