[英]Autofac factory for a static method
I have a component in my application with an interface that looks like this: 我的应用程序中有一个组件,其界面如下所示:
interface ILogger : IService
{
Task LogAsync(Message message);
}
I need to construct these instances using a static method: 我需要使用静态方法构造这些实例:
ILogger logger = ServiceProxy.Create<ILogger>(new Uri(...), new ServicePartitionKey(...));
This is problematic for my unit testing so I am instantiating with a delegate factory with Autofac: 这对我的单元测试来说是有问题的,所以我使用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(...);
}
}
I am registering in Autofac like so: 我正在注册Autofac,如下所示:
builder.Register<ILogger>(ctx => (uri, key) => ServiceProxy.Create<ILogger>(uri, key));
You can do what you want by implementing IRegistrationSource
您可以通过实施
IRegistrationSource
来执行您想要的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;
}
}
}
You would have to register it like this : 你必须这样注册:
builder.RegisterSource(new FactoryRegistrationSource<ILogger>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.