4

我是 StructureMap 的新手,一段时间以来我一直在尝试修复该错误。只是无法弄清楚如何解决它以及我在哪里做错了。我什至建立了一个模板 MVC4 站点,其中没有任何内容,但仍然出现该错误。

有人可以帮我吗?

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

                        x.For<IDbSession>().Use(() => MvcApplication.DbSession);
                        x.For<IDbService>().Use<DbService>();
                    });
        return ObjectFactory.Container;
    }
}

public class HomeController : Controller
{
    protected readonly IDbService _dbService;

    public HomeController(IDbService dbService)
    {
        _dbService = dbService;
    }

    ...
}

public interface IDbSession : IDisposable
{
    void Commit();
    void Rollback();
}

public interface IDbService
{
    StudentsService Students { get; }
    CoursesService Courses { get; }
    ...
}

public class DbService : IDbService
{
    private readonly IDbSession _dbSession;        

    public StudentsService Students { get; }
    public CoursesService Courses { get; }
    ...

    public DbService(IDbSession dbSession)
    {
        _dbSession = dbSession;
    }
}

public class MvcApplication : System.Web.HttpApplication
    {
        private static readonly string _connectionString;
        private static readonly IDbSessionFactory _dbSessionFactory;

        public static IDbSession DbSession
        {
            get { return (IDbSession)HttpContext.Current.Items["Current.DbSession"]; }
            private set { HttpContext.Current.Items["Current.DbSession"] = value; }
        }

        static MvcApplication()
        {
            _connectionString= ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            _dbSessionFactory = new DbSessionFactory(_connectionString);
        }

        protected MvcApplication()
        {
            BeginRequest += delegate
            {
                DbSession = _dbSessionFactory.Create();
            };

            EndRequest += delegate
            {
                if (DbSession != null)
                    DbSession.Dispose();
            };
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
4

1 回答 1

5

您必须配置依赖解析器以处理控制器构造函数中的参数。你可以在这里找到如何:http ://ardalis.com/How-Do-I-Use-StructureMap-with-ASP.NET-MVC-3

于 2013-02-08T08:07:04.480 回答