Search This Blog

Tuesday, July 30, 2019

Autofac

Example:

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.

using Autofac;

using System;


namespace AutofacDemo
{
    class Program
    {
        private static IContainer Container { get; set; }
        static void Main(string[] args)
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<Output>().As<IOutput>();
            builder.RegisterType<DateWriter>().As<IDateWriter>();
            //New Date Class Register With Date Interface
            // Override Date Writer method with New Date Writer Method
            builder.RegisterType<NewDateWriter>().As<IDateWriter>();
            Container = builder.Build();

            WriteDate();

            Console.ReadLine();
        }

        private static void WriteDate()
        {
            using (var scope = Container.BeginLifetimeScope())
            {
                var writer = scope.Resolve<IDateWriter>();
                writer.WriteDate();
            }
        }
    }

    public interface IOutput
    {
        void Write(string content);
    }

    public class Output : IOutput
    {
        public void Write(string content)
        {
            Console.WriteLine(content);
        }
    }

    public interface IDateWriter
    {
        void WriteDate();
    }

    public class DateWriter : IDateWriter
    {
        private IOutput _output;
        public DateWriter(IOutput output)
        {
            _output = output;
        }
        public void WriteDate()
        {
            _output.Write(DateTime.Today.ToShortDateString());
        }
    }

    public class NewDateWriter : IDateWriter
    {
        private IOutput _output;
        public NewDateWriter(IOutput output)
        {
            _output = output;
        }
        public void WriteDate()
        {
            _output.Write(DateTime.Today.AddDays(1).ToShortDateString());
        }
    }
}


Add Autofac Reference from Nuget 







No comments:

Post a Comment


This is a User Friendly Blog.
Simple Interface and Simple Controls are used.
Post your comments so i can modify blog regarding your wish.