瀏覽標籤:

DI Framework

[C#][ASP.NET MVC5][Autofac] DI Framework – AutofacConfig.cs

之前嘗試很多次都失敗,這次終於成功註冊Controller、Service與Repository了,來記錄一下設定檔。

  • AutofacConfig.cs
    /// <summary>
    /// DI設定檔
    /// </summary>
    public class AutofacConfig
    {
    	/// <summary>
    	/// 註冊DI注入物件資料
    	/// </summary>
    	public static void Register()
    	{
    		// 容器建立者
    		ContainerBuilder builder = new ContainerBuilder();
    
    		// 註冊Controllers
    		builder.RegisterControllers(Assembly.GetExecutingAssembly());
    
    		// 註冊Service
    		builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
    			   .Where(t => t.Name.EndsWith("Service"))
    			   .AsSelf();
    
    		// 註冊Repository
    		builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
    			   .Where(t => t.Name.EndsWith("Repository"))
    			   .AsSelf();
    
    		// 建立容器
    		IContainer container = builder.Build();
    
    		// 解析容器內的型別
    		AutofacDependencyResolver resolver = new AutofacDependencyResolver(container);
    
    		// 建立相依解析器
    		DependencyResolver.SetResolver(resolver);
    	}
    }
  • Global.asax
    protected void Application_Start()
    {
        //加入這行
        AutofacConfig.Register();
    }