# 注册服务

//创建Autofac容器
ContainerBuilder containerBuilder = new ContainerBuilder();
//注册服务
containerBuilder.RegisterType<TestService>.As<ITestService>();
//得到Container
IContainer container = containerBuilder.Build();
//得到服务实例
ITestService testService = container.Resolve<ITestService>();
//使用服务
testService.Show();

注册复杂服务

var builder = new ContainerBuilder();

Assembly[] assemblies = BuildManager.GetReferencedAssemblies()
                       .Cast<Assembly>().ToArray();
//属性注入 所有Controller
builder.RegisterControllers(assemblies.ToArray()).PropertiesAutowired();
//注册所有的ApiControllers
builder.RegisterApiControllers(assemblies.ToArray()).PropertiesAutowired(); 

//基于接口IDependency
var baseType = typeof(IDependency);
builder.RegisterAssemblyTypes(assemblies.ToArray())
	  .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
	  .AsImplementedInterfaces()
	  .InstancePerDependency()
	  .PropertiesAutowired();

//泛型仓储注入
builder.RegisterGeneric(typeof(Repository<>))
       .As(typeof(IRepository<>))
	   .AsImplementedInterfaces()
	   .InstancePerDependency()
	   .PropertiesAutowired();

container = builder.Build();

//注册api容器需要使用HttpConfiguration对象
HttpConfiguration config = GlobalConfiguration.Configuration;
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
//设置依赖注入解析器
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

# 注入方式

# 构造函数注入

默认支持构造函数注入

# 属性注入

containerBuilder.RegisterType<TestService>.As<ITestService>().PropertiesAutowired();

# 方法注入

OnActivating/OnActivated:OnActivating在OnActivated前执行。但他们都是在构造函数后执行。

public interface IAnimal
{
    void Say();
}

public class Dog : IAnimal
{
    public string Name { get; set; }
    public void Say()
    {
        Console.WriteLine("汪汪汪!");
        if (!string.IsNullOrEmpty(Name))
        {
            Console.WriteLine("此汪名叫 " + Name);
        }
    }
}

public class Person 
{
    public void Say(IAnimal adopt)
    {
        Console.WriteLine("我领养了一只小动物");
        adopt.Say();
    }
}
var builder = new ContainerBuilder();
builder.RegisterType<Dog>().As<IAnimal>();
builder.RegisterType<Person>().OnActivated(e => 
                               e.Instance.Say(e.Context.Resolve<IAnimal>()));
var container = builder.Build();
var person = container.Resolve<Person>();

# 三种生命周期

InstancePerDependency:默认模式,每次调用,都会重新实例化对象;每次请求都创建一个新的对象。
SingleInstance:单例模式,在整个进程中,对象永远都是同一个实例。
InstancePerLifetimeScope:同一个生命周期范围内是同一个实例,不同的生命周期范围,实例不一样。

# 通过配置的方式

# .NET MVC项目

  • AutofacExt帮助类
using Autofac;
using Autofac.Configuration;
using Microsoft.Extensions.Configuration;

namespace autofacConsole
{
    public static class AutofacExt
    {
        private static IContainer _container;

        public static void InitAutofac()
        {

            // Add the configuration to the ConfigurationBuilder.
            var config = new ConfigurationBuilder();
            config.AddJsonFile("autofac.json");

            // Register the ConfigurationModule with Autofac.
            var module = new ConfigurationModule(config.Build());
            var builder = new ContainerBuilder();
            builder.RegisterModule(module);


            // Set the dependency resolver to be Autofac.
            _container = builder.Build();

        }

        /// <summary>
        /// 从容器中获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static T GetFromFac<T>()
        {
            return _container.Resolve<T>();
            //   return (T)DependencyResolver.Current.GetService(typeof(T));
        }

        public static T GetFromFac<T>(string name)
        {
            return _container.ResolveNamed<T>(name);
        }
    }
}
  • 客户端调用
public interface IOutput
{
	void Write(string content);
}

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

class Program
{        
	static void Main(string[] args)
	{
	   AutofacExt.InitAutofac();
		var writer =AutofacExt.GetFromFac<IOutput>();
		writer.WriteDate();
		Console.ReadKey();
	}
}    

json配置文件配置,记得将配置文件设置为:如果较新则复制

{
  "defaultAssembly": "autofacConsole",
  "components": [
    {
      "type": "autofacConsole.ConsoleOutput, autofacConsole",
      "services": [
        {
          "type": "autofacConsole.IOutput,autofacConsole"
        }
      ],
      "instanceScope": "single-instance",
      "injectProperties": true
    }
  ]
}

# .NET CORE项目

  • 管理Nuget包,引入3个程序集。
    autofc_json

  • 新建一个配置文件【autofac.json】,记得将配置文件设置为:始终复制到目录。
    autofc_json

  • 在【Startup.cs】的【ConfigureServices】中注册服务。 autofc_json