2012-08-31 153 views
10

我將一個ASP.NET MVC3項目轉換爲MVC4。我試圖找到使用StructureMap和MVC4的最佳方法。我找到了一些解決方案,可以工作,但還沒有嘗試過。asp.net MVC 4與StructureMap

第一個解決方案非常簡單,並且lightweight。第二個(Structuremap.MVC4)依賴於WebActivator的啓動。

什麼是更好和最簡單的方法?我是否仍然需要引導所有內容並使用WebActivator設置DependencyResolver?

感謝您的幫助。

回答

14

我做了以下,它的工作原理。希望能幫助到你。

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

感謝您help.I'll嘗試你的代碼,我會盡快給你一些反饋。 – LeftyX

+1

您返回服務集合的部分應更改爲_container.GetAllInstances(serviceType).Cast () –