2011-05-12 3 views
1

ASP.NET MVC 1.0에는 어떤 Autofac 버전을 사용해야합니까? 또한 리포지토리 패턴을 사용하여 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을 게시 한) : Global.asax.cs에서

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 : 나는 여기에 내 질문을 게시하기 전에이 페이지의 오른쪽에보고 된 것을 기대했다

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

+0

모르겠다 - 결코 사용하지 않았다 ... –

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

안녕하세요, Todd, Autofac이 자동으로 Repositories/Interfaces를 자동으로 등록하는 방법이 있습니까? 아니면 개별적인 수동으로 자동으로해야합니까? StructureMap에는 어셈블리를 스캔하고 필요한 모든 구성 요소를 등록 할 수있는 규칙이 있습니다. 감사. – Saxman

+0

AutofacControllerModule을 호출하면 자동으로 수행됩니다. 다른 어셈블리 참조 만하십시오. –

관련 문제