Search code examples
c#asp.net-mvcdependency-injectionstructuremapstructuremap4

Can't using StructureMap 4.5.2 in Asp.net MVC


I'm new to StructureMap and i'm using version 4.5.2. I registered my DataContext with StructureMap in Global.asax like this:

void Application_Start(object sender, EventArgs e)
    {
        SetupIcoContainer();

        // Code that runs on application startup
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

    private void SetupIcoContainer()
    {
        var container = new StructureMap.Container(_ =>
        {
            _.For<Data.IUnitOfWork>().Singleton().Use(x => new Data.Database.DataContext());
        });
    }

and I'm using the dependency in my repository class like this:

var uow = new StructureMap.Container().GetInstance<Data.IUnitOfWork>();

but i get this error:

No default Instance is registered and cannot be automatically determined for type 'Data.IUnitOfWork'

The Data.IUnitOfWork, Data.Database.DataContext and my Repository class are in another assembly. The StructureMap doesn't register the DataContext.

Thanks


Solution

  • var uow = new StructureMap.Container();
    

    instantiates a new empty container that does not know IUnitOfWork.

    You can try to set a global static variable in global.asax.cs

    The best way is to use StructureMap as MVC DependencyResolver

    Here there is a way How to get the Structuremap IContainer instance from Asp.Net MVC 5 Dependency Resolver