DarthVader
DarthVader

Reputation: 55022

Structuremap Configuration with generics

I have IRepository interface with which i want to use NHibernateRepository.

How do i configure it with structure map?

protected void ConfigureDependencies()
{
    ObjectFactory.Initialize(
        x =>
            {
                x.For<ILogger>().Use<Logger>();
                x.For<IRepository<T>>().Use<NHibernateRepository<T>>();
            }
        );
}

I m getting an error on T.

Upvotes: 2

Views: 236

Answers (4)

yamen
yamen

Reputation: 15618

This line is expecting a substitution for the generic parameter T:

x.For<IRepository<T>>().Use<NHibernateRepository<T>>();

That is, which type T will be stored in the repository? You've chosen the NHibernateRepository class as the implementation for IRepository, but haven't shown which internal class will be stored.

Alternatively, look at using non-generic IRepository, see here: Generic repository - IRepository<T> or IRepository

Upvotes: 0

Filippo Pensalfini
Filippo Pensalfini

Reputation: 1714

Have a look at this article. Basically, what you want to do is something like this:

public void ConfigureDependencies()
{
    ObjectFactory.Initialize(x => x.Scan(cfg =>
    {
        cfg.TheCallingAssembly();
        cfg.IncludeNamespaceContainingType<Logger>();
        cfg.ConnectImplementationsToTypesClosing(typeof(NHibernateRepository<>));
    }));
}

Regarding the ApplicationContext static class: if you really have a cross-cutting concern, then I see nothing really wrong with it.

Upvotes: 0

Joshua Flanagan
Joshua Flanagan

Reputation: 8557

If you want to be able to map all closing types of IRepository<> to the corresponding closing type for NHibernateRepository<>, use:

x.For(typeof(IRepository<>)).Use(typeof(NHibernateRepository<>))

Upvotes: 2

Travis J
Travis J

Reputation: 82267

Perhaps replace <T> with dynamic?

x.For<IRepository<dynamic>>().Use<NHibernateRepository<dynamic>>();

As for the second point, the Singleton / Service Locator pattern is a rather heated debate.

Upvotes: 0

Related Questions