在C#中,可以使用Attribute來實現依賴注入,具體步驟如下:
[AttributeUsage(AttributeTargets.Property)]
public class InjectAttribute : Attribute
{
}
public class UserService
{
[Inject]
public ILogger Logger { get; set; }
public void DoSomething()
{
Logger.Log("Doing something...");
}
}
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);
}
}
}
static void Main(string[] args)
{
DependencyContainer container = new DependencyContainer();
container.Register<ILogger, ConsoleLogger>();
UserService userService = new UserService();
container.Resolve(userService);
userService.DoSomething();
}
通過以上步驟,就可以在C#中使用Attribute來實現依賴注入了。