Autofacの小例

15044 ワード

AutoFacはNetプラットフォーム下のIOC容器製品.今日はその使い方を勉強します.
1.最も簡単な使用.
    public interface ITestDao
    {
        string SayHello();
    }
    public class TestDao : ITestDao
    {
        public string SayHello()
        {
            return "hello world!";
        }
    }
    

            var builder = new ContainerBuilder();
            builder.RegisterType<TestDao>().As<ITestDao>();

            IContainer container = builder.Build();
            var tdao = container.Resolve<ITestDao>();
            string saystr = tdao.SayHello();        
builder.RegisterType<TestDao>().As<ITestDao>(); TestDao ITestDao 。


2. mvc
    public interface ITestDao
    {
        string SayHello();
    }
    public class TestDao : ITestDao
    {
        public string SayHello()
        {
            return "hello world!";
        }
    }
    

    public class HomeController : Controller
    {

        private ITestDao _testDao;

        public HomeController(ITestDao testDao) 
        {
            this._testDao = testDao;
        }

        public ActionResult Index()
        {

            string saystr = _testDao.SayHello();

            return View();
        }

    }

Globalでasaxには数行のコードを追加する必要があります
  public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // 
            var builder = new ContainerBuilder();
            SetupResolveRules(builder);
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));


            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        private void SetupResolveRules(ContainerBuilder builder)
        {
            builder.RegisterType<TestDao>().As<ITestDao>();
        }
    }


3.プロファイルに登録コードを入れます.
    public interface ITestDao
    {
        string SayHello();
    }
    public class TestDao : ITestDao
    {
        public string SayHello()
        {
            return "hello world!";
        }
    }
    

    public class HomeController : Controller
    {

        private ITestDao _testDao;

        public HomeController(ITestDao testDao) 
        {
            this._testDao = testDao;
        }

        public ActionResult Index()
        {

            string saystr = _testDao.SayHello();

            return View();
        }

    }

Globalでasaxには数行のコードを追加する必要があります
    protected void Application_Start()
        {
            // 
            var builder = new ContainerBuilder();
            builder.RegisterModule(new ConfigurationSettingsReader("autofac")); 
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));


            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

Web.configプロファイルの追加
<configSections>
    <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" />
  </configSections>
<autofac defaultAssembly="MvcApplication11">
    <components>
      <component type="MvcApplication11.Models.TestDao" service="MvcApplication11.Models.ITestDao" />
    </components>
  </autofac>

 4.システムは自動的に登録され、手動の構成とxmlファイルの構成を省略します.(2014-07-16補足)
基本的なインタフェースを書いて、あなたのすべてのインタフェースがこのインタフェースを実現するようにします.このインタフェースが果たす役割は識別の役割だけです.
    public interface IAutofac// 
    {

    }
    public interface ITestDao : IAutofac
    {
        string SayHello();
    }
    public class TestDao : ITestDao
    {
        public string SayHello()
        {
            return "hello world!";
        }
    }
    
    public class HomeController : Controller
    {

        private ITestDao _testDao;

        public HomeController(ITestDao testDao) 
        {
            this._testDao = testDao;
        }

        public ActionResult Index()
        {

            string saystr = _testDao.SayHello();

            return View();
        }

    }

それからGlobalを変更します.ASX内のコード、AppDomain.CurrentDomain.GetAssemblies()は、現在のプログラムドメイン内のすべてのプログラムセットを取得し、RegisterAssemblyTypeにIAutofacを継承したすべてのインタフェースを自動的に登録させます.
        protected void Application_Start()
        {
            // 
            var builder = new ContainerBuilder();
            //builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
            
            var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();
            builder.RegisterAssemblyTypes(assemblys.ToArray())
                .Where(e => typeof(IAutofac).IsAssignableFrom(e) && e != typeof(IAutofac))
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));



            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }