我的应用程序中有一个组件,其界面如下所示:
interface ILogger : IService
{
Task LogAsync(Message message);
}
我需要使用静态方法构造这些实例:
ILogger logger = ServiceProxy.Create<ILogger>(new Uri(...), new ServicePartitionKey(...));
这对我的单元测试来说是个问题,所以我使用Autofac代理工厂进行实例化:
public class LogConsumer
{
private Func<Uri, ServicePartitionKey, ILogger> _logFactory;
public LogConsumer(Func<Uri, ServicePartitionKey, ILogger> logFactory)
{
_logFactory = logFactory;
}
public async Task MethodThatUsesLogger()
{
ILogger logger = _logFactory(new Uri(...), new ServicePartitionKey(...));
await logger.LogAsync(...);
}
}
我正在注册Autofac:
builder.Register<ILogger>(ctx => (uri, key) => ServiceProxy.Create<ILogger>(uri, key));
答案 0 :(得分:3)
您可以通过实施IRegistrationSource
class FactoryRegistrationSource<TService> : IRegistrationSource
{
public Boolean IsAdapterForIndividualComponents
{
get
{
return false;
}
}
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
IServiceWithType typedService = service as IServiceWithType;
if (typedService == null)
{
yield break;
}
if (typedService.ServiceType == typeof(TService))
{
IComponentRegistration registration = RegistrationBuilder.ForDelegate<Func<Uri, TService>>((c, p) => ((Uri uri) => Factory.Get<TService>(uri)))
.CreateRegistration();
yield return registration;
}
}
}
你必须这样注册:
builder.RegisterSource(new FactoryRegistrationSource<ILogger>());