首页 > 其他 > 详细

Autofac Getting Started

时间:2019-01-21 18:40:51      阅读:150      评论:0      收藏:0      [点我收藏+]

https://autofaccn.readthedocs.io/en/latest/getting-started/index.html

The basic pattern for integrating Autofac into your application is:

  • Structure your app with inversion of control (IoC) in mind.
  • Add Autofac references.
  • At application startup…
  • Create a ContainerBuilder.
  • Register components.
  • Build the container and store it for later use.
  • During application execution…
  • Create a lifetime scope from the container.
  • Use the lifetime scope to resolve instances of the components.

This getting started guide walks you through these steps for a simple console application. Once you have the basics down, you can check out the rest of the wiki for more advanced usage and integration information for WCF, ASP.NET, and other application types.

 class Program
    {
        private static IContainer Container { get; set; }

        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<ConsoleOutput>().As<IOutput>();
            builder.RegisterType<TodayWriter>().As<IDateWriter>();
            Container = builder.Build();

            // The WriteDate method is where we‘ll make use
            // of our dependency injection. We‘ll define that
            // in a bit.
            WriteDate();

            Console.ReadLine();
        }

        public static void WriteDate()
        {
            // Create the scope, resolve your IDateWriter,
            // use it, then dispose of the scope.
            using (var scope = Container.BeginLifetimeScope())
            {
                var writer = scope.Resolve<IDateWriter>();
                writer.WriteDate();
            }
        }
    }
  • The “WriteDate” method asks Autofac for an IDateWriter.
  • Autofac sees that IDateWriter maps to TodayWriter so starts creating a TodayWriter.
  • Autofac sees that the TodayWriter needs an IOutput in its constructor.
  • Autofac sees that IOutput maps to ConsoleOutput so creates a new ConsoleOutput instance.
  • Autofac uses the new ConsoleOutput instance to finish constructing the TodayWriter.
  • Autofac returns the fully-constructed TodayWriter for “WriteDate” to consume.

 

Autofac Getting Started

原文:https://www.cnblogs.com/chucklu/p/10300239.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!