在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来实现依赖注入了。