asp.net core使用autofac作为服务注册容器

1.引用nuget包

<PackageReference Include="Autofac" Version="6.0.0" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />

2.创建接口和实现类

   public interface IMyService
    {
        void print();
    }
     public class MyService : IMyService
    {
        public void print()
        {
            Console.WriteLine("hello");
        }
    }

3.创建服务注册模块类

public class MyServicesModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // 注册服务
            builder.RegisterType<MyService>().As<IMyService>().InstancePerLifetimeScope();
        }
    }

4.在program中使用autofac容器

 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory(p => { p.RegisterModule<MyServicesModule>(); }));

5.在控制器或其他需要使用依赖注入的类中注入服务

public class MyController : Controller
{
    private readonly IMyService _myService;

    public MyController(IMyService myService)
    {
        _myService = myService;
    }

    // 使用_myService...
}

你可能感兴趣的:(asp.net)