简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM