2011-05-12 50 views
1

什麼Autofac版本應該用於ASP.NET MVC 1.0。另外,有哪些示例可用於使用存儲庫模式的ASP.NET MVC?Autofac - 用於ASP.NET MVC 1和示例的什麼版本?

public class MyController : BaseController 
{ 
    private readonly IUser _user; 
    private readonly ICompany _company; 

    public MyController(IUser user, ICompany company) 
    { 
     _user = user; 
     _company = company; 
    } 

    public ActionResult Index() 
    { 
     // Actions 
    } 
} 

回答

0

我已經決定使用StructureMap我的應用程序。這裏就是我做,使其工作:

創建我自己的CustomFactory類:

public class StructureMapControllerFactory : DefaultControllerFactory 
{ 
    protected override IController GetControllerInstance(Type controllerType) 
    { 
     if (controllerType == null) 
     { 
      return base.GetControllerInstance(controllerType); 
     } 

     try 
     { 
      return ObjectFactory.GetInstance(controllerType) as Controller; 
     } 
     catch (StructureMapException ex) 
     { 
      throw; 
     } 
    } 
} 

創建一個引導程序,使用StructureMap公約註冊的所有接口和我的裝配實現。 (我已經張貼在這個blog post):

public class StructureMapBootstrapper : IBootstrapper 
{ 
    private static bool hasStarted; 

    public void BootstrapStructureMap() 
    { 
     ObjectFactory.Initialize(x => 
     { 
      x.AddRegistry<FactoryRegistry>(); 
     }); 
    } 

    public static void Restart() 
    { 
     if (hasStarted) 
     { 
      ObjectFactory.ResetDefaults(); 
     } 
     else 
     { 
      Bootstrap(); 
      hasStarted = true; 
     } 
    } 

    public static void Bootstrap() 
    { 
     new StructureMapBootstrapper().BootstrapStructureMap(); 
    } 
} 

public class FactoryRegistry : Registry 
{ 
    public FactoryRegistry() 
    { 
     Scan(s => 
     { 
      s.Assembly("Calendar.Library"); 
      s.TheCallingAssembly(); 
      s.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", "").ToLower()); 
      s.WithDefaultConventions(); 
     }); 
    } 
} 

註冊StructureMap在Global.asax.cs中:

protected void Application_Start() 
{ 
    StructureMapBootstrapper.Bootstrap(); 
    ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory()); 
} 
1

我不認爲你可以使用它。按照http://code.google.com/p/autofac/wiki/MvcIntegration只支持MVC2。

+0

我看着這個頁面之前,我張貼了我的問題在這裏,並希望有人會指我到正確的版本。太糟糕了,它不被支持。 StructureMap怎麼樣,它支持ASP.NET MVC 1嗎?謝謝。 – Saxman 2011-05-12 16:29:43

+0

不知道 - 從來沒有使用它... – 2011-05-12 16:42:09

1

對於ASP.NET MVC1,您可以使用Autofac 1.4.1到1.4.4。我正在運行1.4.2。下面是Autofac 1.4.2的示例引導程序(刪除了一些代碼片段,不知道1.4.4中可能會影響該代碼的更改)。

namespace Web 
{ 
    public class PropertyInjectionForAllComponents : Module 
    { 
     protected override void AttachToComponentRegistration (IContainer container, IComponentRegistration registration) 
     { 
      registration.Activating += ActivatingHandler.InjectProperties; 
     } 
    } 

    public static class Bootstrapper 
    { 
     public static IContainerProvider ConfigureAutofac (string serverPath) 
     { 
      var configManager = new ConfigManager (new ConfigurationManagerWrapper()); 

      string environment = configManager.AppSettings ("Environment"); 

      RequireSslAttribute.Enable = configManager.AppSettings ("EnableSSL").IsTrue(); 

      // Autofac IoC configuration see http://www.codeproject.com/KB/architecture/di-with-autofac.aspx for details 
      // ExternallyOwned() - Use on objects that are disposable which you do not want disposed such as Console.Out as an implementation TextWriter. 
      // OnActivating() - Allows property injection 
      // SingletonScoped() - Only one instance of the class will ever be created for the process. This is the default behavior. 
      // FactoryScoped() - Each time a component is requested from the container, a new instance will be created. 
      // ContainerScoped() - This provides the flexibility needed to implement per-thread, per-request, or per-transaction component life-cycles. 
      // HttpRequestScoped() - Means that at most one instance of the component will be created for each incoming web request. This is handy for items that should be shared within a single request, e.g. repositories. 
      var builder = new ContainerBuilder(); 

      // SCIBS.Core components 
      builder.Register (c => new HttpContextWrapper (HttpContext.Current)).As<HttpContextBase>().HttpRequestScoped(); 
      builder.Register<ElmahLogger>().As<ILogger>().OnActivating (ActivatingHandler.InjectProperties).SingletonScoped(); 
      builder.Register<WebConfigurationManagerWrapper>().WithArguments (new NamedParameter ("applicationVirtualPath", HostingEnvironment.ApplicationVirtualPath)).As<IConfigurationManager>().SingletonScoped(); 
      builder.Register<ConfigManager>().As<IConfigManager>().SingletonScoped(); 
      builder.Register<AppSettings>().As<IAppSettings>().SingletonScoped(); 
      builder.Register<SparkTemplate>().As<ITemplate>().SingletonScoped(); 
      builder.Register<Security>().As<ISecurity>().HttpRequestScoped(); 
      builder.Register<MailerService>().WithArguments (new NamedParameter ("mailLogger", new Log4NetLogger ("EmailLogger"))).As<IMailerService>().FactoryScoped(); 

      builder.Register<QuoteService>().As<IQuoteService>().FactoryScoped(); 
      builder.Register<OrderService>().As<IOrderService>().FactoryScoped(); 

      builder.Register<AccountRepository>().As<IAccountRepository>().FactoryScoped(); 

      builder.Register<ContactService>().As<IContactService>().FactoryScoped(); 
      builder.Register<AccountService>().As<IAccountService>().FactoryScoped(); 
      builder.Register<AddressService>().As<IAddressService>().FactoryScoped(); 
      builder.Register<AspNetMembershipProvider>().As<IMembershipProvider>().FactoryScoped(); 

      var autofacControllerModule = new AutofacControllerModule (System.Reflection.Assembly.GetExecutingAssembly()); 
      autofacControllerModule.ActivatingHandler += ActivatingHandler.InjectProperties; 
      builder.RegisterModule (autofacControllerModule); 

      builder.RegisterModule (new PropertyInjectionForAllComponents()); 

      IContainerProvider containerProvider = new ContainerProvider (builder.Build()); 
      ControllerBuilder.Current.SetControllerFactory (new AutofacControllerFactory (containerProvider)); 

      return containerProvider; 
     } 
    } 
} 

以及它如何從您的應用程序調用:

public class MvcApplication : HttpApplication, IContainerProviderAccessor 
{ 
    private static IContainerProvider _containerProvider; 

    public IContainerProvider ContainerProvider 
    { 
     get 
     { 
      return _containerProvider; 
     } 
    } 

    protected void Application_Start() 
    { 
     Log.Info ("Application_Start"); 

     string serverPath = Server.MapPath ("~"); 
     _containerProvider = Bootstrapper.ConfigureAutofac (serverPath); 

     var configManager = ContainerProvider.RequestContainer.Resolve<IConfigManager>(); 
     EnableSSL = configManager.AppSettings ("EnableSSL").IsTrue(); 

     RegisterRoutes (RouteTable.Routes); 

     // NOTE: http://stackoverflow.com/questions/2854024/how-to-prevent-debug-assert-to-show-a-modal-dialog 
     var logger = ContainerProvider.RequestContainer.Resolve<ILogger>(); 
     Debug.Listeners.Clear(); 
     Debug.Listeners.Add (new LoggerTraceListener() {Log = logger}); 
    } 
} 
+0

嗨託德,有沒有辦法讓Autofac自動註冊存儲庫/界面,或者我們必須手動爲每個人手動嗎? StructureMap有一個約定,它可以掃描程序集並註冊所需的所有組件。謝謝。 – Saxman 2011-05-12 17:26:17

+0

對AutofacControllerModule的調用爲您做到了。只要給它一個不同的彙編參考。 – 2011-05-16 15:12:40