StructureMap error resolving Open Generic dependency

203 views Asked by At

So I've wired up my open generic plugin in StructureMap like so

scan.ConnectImplementationsToTypesClosing(typeof(IRepository<>));

But still get the dreaded

No Default Instance defined for PluginFamily KharaSoft.Utils.IRepository`1[[KharaSoft.App.Core.DomainObject, KharaSoft.App.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]

I debug after the Container is initialized and see that it does indeed have an instance of RepositoryBase<> registered so it knows what I want done, but it won't close it for me. Is there something I'm missing here?

2

There are 2 answers

0
Michael Brown On BEST ANSWER

So I'm not sure if this is the "best" way but this is what I found that works. I had to explicitly register the open implementation of the plugin like this:

ObjectFactory.Initialize(
  x =>
    {
      x.Scan(scan =>
        {
          scan.Assembly(typeof (IRepository<>).Assembly);
          scan.WithDefaultConventions();
        });
      x.For(typeof (IRepository<>)).Use(typeof (RepositoryBase<>));
      x.For<IUnitOfWork>().Use<MyDataContext>();
    });
return ObjectFactory.Container;

See I didn't want to close the generic directly in all cases. So now my MVC controller can take a dependency like so

public PlayerController(IRepository<Player> players)
{
  Players = players;
}

And StructureMap will close the dependency with an instance of RepositoryBase

1
heads5150 On

It's hard to workout without seeing the full Scan code or your project layout. There are a few default steps I normally go through when I have this issue.

Ensure you have

scan.WithDefaultConventions()

Ensure that the assembly containing the Repository classes is included in the scan:

x.AssemblyContainingType(typeof(UserRepository)); 

Ensure that you have the correct implementations in place:

IRepository<User>

has matching

Repository<User>

Hopefully something amongst this advice might help you find the issue.