Simple use of Autofac and simple use of Autofac
Record the process of learning Autofac today.
I have been confused about IoC and DI before. I have a preliminary understanding of IoC and DI only after studying the articles of my predecessors. Thank you for your selfless dedication!
Article address:
The understanding of dependency injection and control inversion is too good.
Chapter 2 IoC 2.1 IoC basics -- Spring3
What? It is clearly the basic use of recording Autofac...
Okay, go back to the topic.
First, build a time output program:
public interface IOutput{ void Write(string content);}
public class ConsoleOutput : IOutput{ public void Write(string content) { Console.WriteLine(content); }}
public interface IDateWrite{ void WriteDate();}
public class TodayWrite : IDateWrite{ private IOutput _output; public TodayWrite(IOutput output) { this._output = output; } public void WriteDate() { this._output.Write(DateTime.Now.ToShortDateString()); }}
Class Program {static void Main (string [] args ){
// Create an output object leleoutput ConsoleOutput = new consoleOutput ();
// Create a date output object and inject the output object TodayWrite todayWrite = new TodayWrite (consoleOutput) on which the date output object depends by using the constructor );
// Execute the output date method todayWrite. WriteDate (); Console. Read ();}}
The above is the original implementation method. Now we can see that it has a reasonable dependency structure, so we can use it together with Autofac.
First, add the reference of Autofac.
Open tool> choose NuGet Package Manager> Manage NuGet packages for the solution
Do not reference Autofac after installation
using Autofac;
Next, refactor the Program class.
class Program{ private static IContainer Container { get; set; } static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<ConsoleOutput>().As<IOutput>(); builder.RegisterType<TodayWrite>().As<IDateWrite>(); Container = builder.Build(); WriteDate(); Console.Read(); } static void WriteDate() { using (ILifetimeScope scope = Container.BeginLifetimeScope()) { var write = scope.Resolve<IDateWrite>(); write.WriteDate(); } }}
Finally, paste the Autofac document address: Autofac