【发布时间】:2016-04-26 18:28:15
【问题描述】:
我很难在我的应用程序中集成 autofac..
我的应用程序与其他应用程序集成,当与另一个应用程序的连接由合适的“协议”对象维护时
// This class is inherited by a few other classes
public abstract class Protocol
我有一个层由它自己的线程运行并处理连接请求。对于每种类型的请求,都会创建不同类型的协议(不同的协议对象)
// For example lets say every protocol (Inhertiance of Protocol abstract object)
// takes in ctor these 3 services + runtime configuration object:
public Protocol1(IFramingAgent, IFramingAlgorithm, IFramingParser, configObject configuration)
我的协议对象被键控注册为协议。还, 每个服务都使用密钥注册,因为每个协议使用从同一接口继承的不同类型。当然,所有这些都注册为 PerDependency (虽然我不是很了解这个 lifeCycle 与 PerScope 的区别,非常感谢解释)
这是我糟糕的课程:
public class ProtocolsLayer : Layer
{
private IFrameworkDependencyResolver _resolver;
private IConfigurationService _configService;
public ProtocolsLayer(IFrameworkDependencyResolver resolver, IConfigurationService configurationService)
{
_resolver = resolver;
_configService = configurationService;
}
void HandleConnection1()
{
// What I have at the moment (terrible):
// Resolve the fitting services (All keyed - key is received by the type, Resolve and ResolveWithParameters used here are my wrappers)
var agent = _resolver.Resolve<IFramingAgent>(typeof(Protocol1FramingAgent));
var algo = _resolver.Resolve<IFramingAlgorithm>(typeof(Protocol1FramingAlgorith));
var parser = _resolver.Resolve<IFramingParser>(typeof(Protocol1FramingParser));
// A parameter I get and pass to each protocol at runtime
var protocolConfig = _configService.GetConfig<Protocol1Configuration>();
// Finally resolve the protocol with it's parameters:
protocol = _resolver.ResolveWithParameters<IProtocol>(typeof(Protocol1), new List<object>{
agent, resolver, parser, protocolConfig
});
//...
// Theres gotta be a better way!!
}
void HandleConntection2()
{
// Same as in protocol1
}
void HandleConnection3()
{
// Same as in protocol1
}
}
请记住,我不希望引用 autofac,这意味着我不能使用我听到的 IIndex。
谢谢!
【问题讨论】:
标签: c# dependency-injection autofac resolve