溫馨提示×

如何在C#中使用Attribute來實現依賴注入

c#
小樊
158
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女