2023-07-08 乐帮网
.net autofac
在.Net的体系中框架中注入默认采用DI注入,其中有一种动态注入用法如下:
方法一:
services.AddTransient(factory =>
{
Func<string, IGPSParseProvider> accesor = key =>
{
if (key.Equals(GPSEnum.P718D))
{
return factory.GetService<GPSParse1DProvider>();
}
else if (key.Equals(GPSEnum.HLD))
{
return factory.GetService<GPSParse2Provider>();
}
else
{
throw new ArgumentException($"Not Support key : {key}");
}
};
return accesor;
});
方法二:
services.AddSingleton(sp =>
{
var dbProvider = sp.GetService<IDbProvider>();
ILogger<SmartProvider> smartLogger = sp.GetService<ILogger<SmartProvider>>();
var config = dbProvider.GetConfig(Enum.GetName(typeof(ConfigureEnum), ConfigureEnum.BIND));
double bindType = 0;
if (config!= null)
double.TryParse(config.Val, out bindType);
if (faceType == 1 || faceType == 2)
return new SmartProvider(dbProvider, smartLogger) as ILoginProvider;
else if (faceType == 3)
return new ManSignProvider(dbProvider) as ILoginProvider;
else
return new ArcSoftProvider(dbProvider) as ILoginProvider;
});
以上两种方法都是动态注入,主要区别是一个参数内置一个是外置,获取实例时稍微有点差别,如下:
方法一:
public class GPSProvider : IGPSProvider
{
private IGPSParseProvider _gpsParse = null;
private Func<string, IGPSParseProvider> _serviceGpsParse;
public GPSProvider(Func<string, IGPSParseProvider> serviceGpsParse)
{
_serviceGpsParse = serviceGpsParse;
_gpsParse = serviceGpsParse(PSEnum.P718D);
}
}
方法二:
public class LoginViewParse:IView
{
private ILoginProvider _loginProvider;
public LoginViewParse(ILoginProvider loginProvider)
{
_loginProvider = loginProvider;
}
}
那么在Autofac中如何实现以上功能呢?首先肯定是可以实现的,方式如下:
方法一:
builder.Register<IGPSParseProvider>((factory, p) =>
{
var key = p.TypedAs<string>();
if (key.Equals(GPSEnum.P718D))
{
return factory.Resolve<GPSParse718DProvider>();
}
else
{
throw new ArgumentException($"Not Support key : {key}");
}
});
方法二:
builder.Register(factory =>
{
var dbProvider = factory.Resolve<IDbProvider>();
var faceConfig = dbProvider.GetConfig(Enum.GetName(typeof(ConfigureEnum), ConfigureEnum.BIND));
double faceType = 0;
if (faceConfig != null)
double.TryParse(faceConfig.Val, out faceType);
if (faceType == 1 || faceType == 2)
return new SmartProvider(dbProvider, smartLogger, httpFactory, configuration, captureProvider) as ILoginProvider;
else if (faceType == 3)
return new ManSignProvider(dbProvider, manSignLogger, httpFactory, configuration, captureProvider, signProvider) as ILoginProvider;
else
return new ArcSoftProvider(dbProvider, arcLogger, captureProvider, configuration, httpFactory) as ILoginProvider;
});
以上就是Autoface的实现方式。
关注我的微信公众号
在公众号里留言交流
投稿邮箱:1052839972@qq.com
庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。
如果感觉对您有帮助
欢迎向作者提供捐赠
这将是创作的最大动力