StructureMap ActivationException网站加载

时间:2014-02-17 16:29:50

标签: asp.net-web-api inversion-of-control structuremap

我的网站是MVC和WebAPI的混合体。当我第一次加载网站时,似乎我的控制器正在我的IOC容器完全加载之前构建。我第一次调试网站时出现以下错误:

 An exception of type 'Microsoft.Practices.ServiceLocation.ActivationException' occurred in Microsoft.Practices.ServiceLocation.dll but was not handled in user code

 Additional information: Activation error occured while trying to get instance of type PendingCoursesController, key ""

我正在使用StructureMap作为我的容器,并从nuget中删除了包的'structuremap'和'StructureMap.MVC4'。抛出错误的控制器是WebAPI控制器。如果我刷新页面,则控制器构造正确,并且所有内容都按预期加载到页面上。这只是引发错误的初始加载,因此我的页面缺少数据。

public static class IoC {
    public static IContainer Initialize() {
        ObjectFactory.Initialize(x =>
                    {
                        x.Scan(scan =>
                                {
                                    scan.TheCallingAssembly();
                                    scan.WithDefaultConventions();
                                });
                    });
        return ObjectFactory.Container;
    }
}

[assembly: WebActivator.PreApplicationStartMethod(typeof(App_Start.StructuremapMvc), "Start")]
public static class StructuremapMvc {
    public static void Start() {
        IContainer container = IoC.Initialize();
        DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
    }
}

1 个答案:

答案 0 :(得分:1)

添加了这个并修复了它。来自Dependency Injection Structuremap ASP.NET Identity MVC 5

的回答
using MVC.CFC.Domain;
using MVC.CFC.Domain.Data;
using MVC5.CFC.Web.Infrastructure;
using MVC5.CFC.Web.Models;
using StructureMap;

namespace MVC5.CFC.Web.DependencyResolution
{
    public static class IoC
    {
        public static IContainer Initialize()
        {
            ObjectFactory.Initialize(x =>
                        {

                            x.Scan(scan =>
                                    {
                                        scan.TheCallingAssembly();
                                        scan.WithDefaultConventions();
                                    });
                            x.For<IUserDataSource>().HttpContextScoped().Use<IUserDb>();
                            x.For<Microsoft.AspNet.Identity.IUserStore<ApplicationUser>>().Use<Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>>();
                            x.For<System.Data.Entity.DbContext>().Use(() => new ApplicationDbContext());
                        });



            return ObjectFactory.Container;
        }
    }
}
相关问题