asp.net MVC 4 StructureMap [英] asp.net MVC 4 with StructureMap

查看:153
本文介绍了asp.net MVC 4 StructureMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我转换一个ASP.NET MVC3项目MVC4。我试图找到StructureMap和MVC4工作的最佳方法。我发现一对夫妇的解决方案,这可能会工作,但还没有尝试过呢。

I am converting an ASP.NET MVC3 project to MVC4. I was trying to find the best approach to work with StructureMap and MVC4. I've found a couple of solution which might work, but haven't tried them yet.

第一个解决方案是非常简单和轻量级。第二个( Structuremap.MVC4 )取决于WebActivator的启动。

The first solution is very simple and lightweight. The second one (Structuremap.MVC4) depends on WebActivator for the startup.

什么是更好,最简单的方法?难道我还需要引导一切,与WebActivator设置DependencyResolver?

What is the better and simplest approach? Do I still need to bootstrap everything and set the DependencyResolver with the WebActivator?

感谢您的帮助。

推荐答案

我做了以下和它的作品。希望它帮助。

I did the following and it works. hope it helps.

public class StructureMapDependencyResolver : IDependencyResolver
    {
        private readonly IContainer _container;

        public StructureMapDependencyResolver(IContainer container)
        {
            _container = container;
        }

        public object GetService(Type serviceType)
        {
            if (serviceType.IsAbstract || serviceType.IsInterface)
            {

                return _container.TryGetInstance(serviceType);

            }

            return _container.GetInstance(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _container.GetAllInstances<object>().Where(s => s.GetType() == serviceType);
        }

    }

Global.asax中:

Global.asax:

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

        var container = ConfigureDependencies();

        GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new StructureMapDependencyResolver(container));

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes); 
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    public static IContainer ConfigureDependencies()
    { 
        IContainer container = new Container();

        Database.SetInitializer(new DataContextInitializer());
        var dataContext = new DataContext.DataContext();

        container.Configure(x => x.For<IRepository>().Use<Repository>().Ctor<DbContext>().Is(dataContext)); 
        container.Configure(x=>x.For<IUnitOfWork>().Use<UnitOfWork>());

        return container;
    }

这篇关于asp.net MVC 4 StructureMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆