开发者

Registering a Generics Implementation of a Generic Interface in StructureMap

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜