autofac属性注入

凯文软件 / 2024-12-29 / 原文

实验结果是 每一个属性都会被注入


using Autofac;

namespace auto属性选择性注入;

internal class Program
{
    static void Main(string[] args)
    {
        //创建一个容器
        ContainerBuilder builder = new ContainerBuilder();

        //注册UserService
        builder.RegisterType<UserService>().As<IUserService>();
        //注册School
        builder.RegisterType<School>().As<ISchool>();

        builder.RegisterType<Student>().PropertiesAutowired();

        //从容器中解析出对象
        IContainer container = builder.Build();

        var student = container.Resolve<Student>();
        student.show();

        //线程睡眠2秒
        Thread.Sleep(2000);

    }
}


public class UserService : IUserService
{
    public void show()
    {
        Console.WriteLine("UserService 执行");
    }
}

public interface IUserService
{
    void show();
}


public class Student
{
    public IUserService _userService { get; set; }
    public ISchool _school { get; set; }


    public void show()
    {
        Console.WriteLine("Student 执行");
        _userService.show();
        _school.show();
    }
}

public interface ISchool
{
    void show();
}

//学校类
public class School : ISchool
{
    public void show()
    {
        Console.WriteLine("School 执行");
    }
}



image