0
votes

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:

public 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;
    }
}
2
FYI (unrelated to your problem), ObjectFactory already serves as a static gateway, so there is no need to wrap it in your own IoC static class. If you still prefer your own static class, then there is no reason to use StructureMaps - just create a new instance of Container, and pass the initialization block to it's constructor. return that from your Initialize method. - Joshua Flanagan

2 Answers

0
votes

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.

0
votes

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();
    }));