c#

如何在C#中使用Attribute来实现依赖注入

小樊
98
2024-08-12 04:47:36
栏目: 编程语言

在C#中,可以使用Attribute来实现依赖注入,具体步骤如下:

  1. 创建一个自定义的Attribute类,用来标识需要进行依赖注入的类或属性。例如:
[AttributeUsage(AttributeTargets.Property)]
public class InjectAttribute : Attribute
{
}
  1. 在需要进行依赖注入的类中,使用上面定义的Attribute标记需要注入的属性。例如:
public class UserService
{
    [Inject]
    public ILogger Logger { get; set; }

    public void DoSomething()
    {
        Logger.Log("Doing something...");
    }
}
  1. 创建一个依赖注入容器类,用来管理依赖注入的实例。在容器类中,使用反射来扫描标记了InjectAttribute的属性,并通过反射来实例化依赖注入的实例。例如:
public class DependencyContainer
{
    public void Register<TInterface, TImplementation>()
    {
        // 注册接口和实现类的映射关系
    }

    public void Resolve(object obj)
    {
        var properties = obj.GetType().GetProperties()
            .Where(prop => Attribute.IsDefined(prop, typeof(InjectAttribute)));

        foreach (var property in properties)
        {
            var propertyType = property.PropertyType;
            var instance = Activator.CreateInstance(propertyType);

            property.SetValue(obj, instance);
        }
    }
}
  1. 在应用程序中,先注册需要注入的接口和实现类的映射关系,然后在需要依赖注入的地方调用依赖注入容器的Resolve方法进行注入。例如:
static void Main(string[] args)
{
    DependencyContainer container = new DependencyContainer();
    container.Register<ILogger, ConsoleLogger>();

    UserService userService = new UserService();
    container.Resolve(userService);

    userService.DoSomething();
}

通过以上步骤,就可以在C#中使用Attribute来实现依赖注入了。

0
看了该问题的人还看了