StructureMap container with constructor parameters
I have a class, RepositoryManager
, and I am using this class in some of my controllers:
public RepositoryManager
{
public IGenericRepository Repository {get; set;}
public RepositoryManager()
{
Repository = new GenericRepository(new MyEntities());
}
//...
}
I want to move IGenericRepository to a StructureMap Inversion of control (IoC) container
x.For<IGenericRepository>().Use<GenericRepository>().Ctor<MyEntities>("MyEntities");
Then I change my class constructor to that:
public RepositoryManager(IGenericRepository repository)
{
Repository = repository;
}
But the injection didn't work. I also tried to use the [SetterProperty]
attribute on Repository, but still Repository didn't instantiate.
What did I do wrong?
My complete IoC initialization:
publi开发者_StackOverflow社区c static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
x.For<IRepositoryManager>().Use<RepositoryManager>();
x.For<IGenericRepository>().Use<GenericRepository>().Ctor<MyEntities>("MyEntities");
});
return ObjectFactory.Container;
}
}
Basically your IoC initialisation is wrong for IGenericRepository
. Change it to:
x.For<IGenericRepository>().Use(() => new GenericRepository(new MyEntities()));
In such a case, the constructor with parameter MyEntities
will be called and an instance of MyEntities
will be created and passed to that constructor as a parameter.
You do not need to register the concrete types; they will just be resolved by StructureMap. The scanner is already used with default conventions, so for the above example the following registration code is fully sufficient:
ObjectFactory.Initialize(x => x.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.WithDefaultConventions();
}));
精彩评论