我的软件应控制一个或多个设备。程序流程就像它将在所有可用接口上搜索设备并IDevice
为找到的每个设备实例化一个类型的对象。在这里声明,所有这些对象都必须在运行时设置。
使用 Autofac 获得依赖反转 (DI) 一切都必须在开始时进行设置。如果要在运行时使用某些东西,“工厂”就是要使用的东西。因此,让我们深入研究一个示例:
程序开始看起来像这样:
class Program
{
static void Main(string[] args)
{
var container = ContainerConfig.Configure();
using (var scope = container.BeginLifetimeScope())
{
var app = scope.Resolve<IApplication>();
app.Run();
}
}
}
一旦解决了“应用程序”,所有在开始时已知的设置都已设置。然后应用程序启动 ( app.Run()
),搜索设备,然后设置找到的所有设备的列表。现在设置一个设备需要一堆“工厂”,基本上(这就是问题所在)通过“设备”实例化的“每个类一个”。
class Application : IApplication
{
readonly Device.Factory _deviceFactory;
readonly Log.Factory _logFactory;
readonly DateTime.Factory _dateTimeFactory;
readonly Incident.Factory _incidentFactory;
public Application(Device.Factory deviceFactory, Log.Factory logFactory, DateTime.Factory dateTimeFactory, Incident.Factory incidentFactory)
{
_deviceFactory = deviceFactory;
_logFactory = logFactory;
_dateTimeFactory = dateTimeFactory;
_incidentFactory = incidentFactory;
}
public void Run()
{
List<string> listOfDeviceIds = SearchAllDevices();
List<IDevice> listOfDevices = new List<IDevice>;
foreach(string deviceId in listOfDeviceIds)
{
listOfDevices.Add(deviceFactory(_logFactory, _dateTimeFactory, incidentFactory);
}
}
}
“设备”包含一个记录器跟踪某事,在此示例中它将记录时间和事件。因此,一旦设置了新日志,就需要注入一些工厂。
public class Device : IDevice
{
public delegate Device Factory(Log.Factory logFactory, DateTime.Factory dateTimeFactory, Incident.Factory incidentFactory);
readonly DateTime.Factory _dateTimeFactory;
readonly Incident.Factory _incidentFactory;
readonly Log.Factory _logFactory;
List<Log> ListOfLogs = new List<Log>();
public Device(Log.Factory logFactory, DateTime.Factory dateTimeFactory, Incident.Factory incidentFactory)
{
_dateTimeFactory = dateTimeFactory;
_incidentFactory = incidentFactory;
_logFactory = logFactory;
}
public AddLog()
{
ListOfLogs().Add(_logFactory(_dateTimeFactory(), _incidentFactory() ));
}
}
public class Log()
{
public delegate Log Factory();
public IDateTime DateTime() { get; }
public IIncident Incident() { get; }
public Log(IDateTime dateTime, IIncident incident)
{
DateTime = dateTime;
Indicent = incident;
}
}
public DateTime : IDateTime
{
public delegate DateTime Factory();
//...
}
public Indicent : IIndicent
{
public delegate Indicent Factory();
//...
}
现在,这只是对设备类的一点了解,它实际上集成了更多的东西。那就是它现在又变得一团糟了。
在实例化“设备”时,我设置了大约 30 个子类甚至更多。因此,因为它们是在运行时设置的,所以它们都需要一个必须通过其构造函数的“设备”提供的“工厂”。好吧,我想你明白了。
你怎么处理那件事呢?还是我又走错了路?我是否会通过尝试对所有内容进行反向依赖来误解某些内容?
另一点是,整个故事将使其可测试,其中 interface 和 autofac 是关键词。但是当使用工厂时,我总是必须使用它自己的类并且不能使用它的接口作为参考,此时 DI 不再实现。... ?
public class MyClass : IMyClass
{
public delegate MyClass Factory();
// ...
}
使用它将需要MyClass.Factory
而不是IMyClass.Factory
:
class Main()
{
MyClass.Factory _myClassFactory;
Main(MyClass.Factory myClassFactory)
{
_myClassFactory = myClassFactory;
}
foo ()
{
IMyClass myInstance = myClassFactory();
}
}