asp.net MVC 4 with StructureMap

假如想象 提交于 2019-12-03 09:38:18

问题


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.

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

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

Thanks for your help.


回答1:


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:

     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;
    }


来源:https://stackoverflow.com/questions/12218300/asp-net-mvc-4-with-structuremap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!