2012-08-31 16 views
10

Tôi đang chuyển đổi dự án ASP.NET MVC3 thành MVC4. Tôi đã cố gắng tìm cách tiếp cận tốt nhất để làm việc với StructureMap và MVC4. Tôi đã tìm thấy một vài giải pháp có thể hoạt động nhưng chưa thử chúng.asp.net MVC 4 với StructureMap

Giải pháp đầu tiên rất đơn giản và lightweight. Thứ hai (Structuremap.MVC4) phụ thuộc vào WebActivator cho khởi động.

Cách tiếp cận tốt hơn và đơn giản nhất là gì? Tôi vẫn cần phải khởi động mọi thứ và thiết lập DependencyResolver với WebActivator?

Cảm ơn sự giúp đỡ của bạn.

Trả lời

14

Tôi đã làm như sau và hoạt động. hy vọng nó giúp.

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

Cám ơn help.I'll bạn thử code của bạn và tôi sẽ lấy lại cho bạn với một số thông tin phản hồi. – LeftyX

+1

Phần mà bạn trả về một tập hợp các dịch vụ phải được thay đổi thành _container.GetAllInstances (serviceType) .Cast () –