开发者

Registering a Generics Implementation of a Generic Interface in StructureMap

开发者 https://www.devze.com 2022-12-19 13:14 出处:网络
i have a generic interface public interface IDomainDataRepository<T> { T[] GetAll(); } with a generic implementation

i have a generic interface

public interface IDomainDataRepository<T>
{
    T[] GetAll();
}

with a generic implementation

public 开发者_如何学编程class DomainDataRepository<T> : IDomainDataRepository<T>
{
    public virtual T[] GetAll()
    {
        return GetSession().Linq<T>().ToArray();
    }
}

how do I register it in StructureMap so that if I request IDomainDataRepository<State> then it will new up a DomainDataRepository<State>. Furthermore if I decide to implement a CountryDomainDataRepository and I request a IDomainDataRepository<Country> I want to get the specific implementation.

public class CountryDomainDataRepository : IDomainDataRepository<State>
{
    public virtual Country[] GetAll()
    {
        return GetSession().Linq<Country>().ToArray();
    }
}


You can accomplish this by configuring the generic open type to use a concrete open type:

    [TestFixture]
public class open_generic_registration
{
    [Test]
    public void should_resolve_to_the_configured_concrete_instance_of_T()
    {
        var container = new Container(cfg =>
        {
            cfg.For(typeof (IDomainDataRepository<>)).Use(typeof (DomainDataRepository<>));
        });

        container.GetInstance<IDomainDataRepository<string>>().ShouldBeOfType<DomainDataRepository<string>>();
        container.GetInstance<IDomainDataRepository<int>>().ShouldBeOfType<DomainDataRepository<int>>();
        container.GetInstance<IDomainDataRepository<DateTime>>().ShouldBeOfType<DomainDataRepository<DateTime>>();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号