按类型名称进行依赖注入是一种常见的解决方法,它通过类型名称来决定注入哪个具体的实例。以下是一个使用C#语言的代码示例:
// 定义接口
public interface IService
{
void DoSomething();
}
// 实现接口
public class ServiceA : IService
{
public void DoSomething()
{
Console.WriteLine("Service A is doing something.");
}
}
public class ServiceB : IService
{
public void DoSomething()
{
Console.WriteLine("Service B is doing something.");
}
}
// 定义依赖注入容器
public class DependencyContainer
{
private Dictionary _registeredTypes;
public DependencyContainer()
{
_registeredTypes = new Dictionary();
}
// 注册类型
public void RegisterType()
{
string typeName = typeof(TInterface).Name;
_registeredTypes[typeName] = typeof(TImplementation);
}
// 解析类型
public TInterface Resolve()
{
string typeName = typeof(TInterface).Name;
if (_registeredTypes.ContainsKey(typeName))
{
Type type = _registeredTypes[typeName];
return (TInterface)Activator.CreateInstance(type);
}
else
{
throw new InvalidOperationException($"Type {typeName} is not registered.");
}
}
}
// 使用依赖注入容器
public class MyClass
{
private IService _service;
public MyClass(IService service)
{
_service = service;
}
public void DoSomething()
{
_service.DoSomething();
}
}
// 测试代码
public class Program
{
public static void Main(string[] args)
{
DependencyContainer container = new DependencyContainer();
container.RegisterType();
MyClass myClass = new MyClass(container.Resolve());
myClass.DoSomething();
Console.ReadLine();
}
}
在上述示例中,我们首先定义了一个IService
接口,并实现了两个具体的服务类ServiceA
和ServiceB
。然后,我们创建了一个DependencyContainer
类作为依赖注入容器,用于注册和解析不同类型的实例。接下来,我们定义了一个MyClass
类,它依赖于IService
接口。在Main
方法中,我们创建了一个DependencyContainer
对象,并注册了IService
接口的实现类ServiceA
。然后,我们创建一个MyClass
对象,并通过容器解析出IService
实例并传入MyClass
的构造函数。最后,调用MyClass
的DoSomething
方法,会输出Service A is doing something.
。
下一篇:按类型排序字典值