How to use Autofac in C#
By FoxLearn 3/13/2021 1:48:48 PM 16.34K
This post shows you how to use Autofac in C# .NET
What is autofac c#
Autofac is an addictive IoC (Inversion of Control) container for .NET Core, ASP.NET Core, .NET 4.5.1+, Universal Windows apps, and more. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity.
First off, You can create a new console project called AutofacDemo
Next, Right click on your project select Manage NuGet Packages -> Search autofac -> install
After you finish installing the library, you can create an interface called IConnection
public interface IConnection { void Connect(); void Command(string command); }
Create MySqlConnection inherit from IConnection, then implement Command, Connect methods as shown below.
public class MySqlConnection : IConnection { public void Command(string command) { Console.Write("Execute MySql command: {0}", command); } public void Connect() { Console.WriteLine("Connect to MySql Server..."); } }
Similarly, create SqlConnection inherit from IConnection
public class SqlConnection : IConnection { public void Command(string command) { Console.Write("Execute Sql command: {0}", command); } public void Connect() { Console.WriteLine("Connect to Sql Server..."); } }
Finally, Create an AppService class to manage the instance you want to create
public static class AppService { static IContainer Container { get; set; } static AppService() { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<MySqlConnection>().As<IConnection>();//Change your instance you want to create Container = builder.Build(); } public static IConnection Connection => Container.Resolve<IConnection>(); }
You can call Connect, Command method in Main method
class Program { static void Main(string[] args) { AppService.Connection.Connect(); AppService.Connection.Command("Insert"); Console.ReadLine();//Wait } }
You can easily to change the instance you want to create, we don't need to change code in the Main method
builder.RegisterType<SqlConnection>().As<IConnection>();//Change your instance you want to create
Press F5 to run your program