使用以下套件
1
NuGet\Install-Package Autofac -Version 6.3.0
Code Example
使用下來,覺得在使用MVC的時候效果最明顯
Autofac
1
NuGet\Install-Package Autofac -Version 6.3.0
Autofac.Mvc5
1
NuGet\Install-Package Autofac.Mvc5 -Version 6.1.0
建立要使用DI的Class與Interface
1
2
3
4
5
6
7
8
9
10
11
12
public interface ILogger
{
void Log(string msg);
}
public class Logger : ILogger
{
public void Log(string msg)
{
Console.WriteLine("LOG:" + msg);
}
}
建立用來實現DI的Class,例如AutofacConfig.cs
AutofacConfig.cs 內部長這樣
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using Autofac;
using Autofac.Integration.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace AutofacMVC.App_Start
{
public class AutofacConfig
{
public static void Run()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<Logger>().As<ILogger>();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
在Global.asax 添加Method
最後在Controoler正在使用DI注入例如
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using AutofacMVC.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AutofacMVC.Controllers
{
public class HomeController : Controller
{
protected ILogger Logger;
public HomeController(ILogger logger)
{
Logger= logger;
}
public ActionResult Index()
{
return View();
}
}
}