在使用AufoFac中如果一个接口有多种实现,项目中需要手动解析
IAms_assetsService _service = AutofacDependencyResolver.Current.RequestLifetimeScope.ResolveNamed<IService>("assetsService");
注册是可以使用代码如
builder.RegisterType<Ams_assetsService>().Named<IAms_assetsService>("assetsService").PropertiesAutowired().InstancePerLifetimeScope();
builder.RegisterType<ProxyAms_assetsService>().Named<IAms_assetsService>("ProxyassetsService").PropertiesAutowired().InstancePerLifetimeScope();
配置文件方法如
<?xml version="1.0" encoding="utf-8"?>
<autofac>
<components>
<component type="MyMis.Service.Ams_assetsService,MyMis.Service" service="MyMis.IService.IAms_assetsService,MyMis.IService" instance-scope="PerLifetimeScope" inject-properties="true" name="assetsService"/>
<component type="MyMis.Service.ProxyAms_assetsService,MyMis.Service" service="MyMis.IService.IAms_assetsService,MyMis.IService" instance-scope="PerLifetimeScope" inject-properties="true" name="ProxyassetsService"/>
</components>
</autofac>
不过这样解析比较麻烦,代码中需要引用using Autofac;
using Autofac.Integration.Mvc;网上看到有方法吧解析的方法独立出来,这个办法挺好
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyMis.Entities;
using MyMis.DTO;
using MyUtility.Interface;
namespace MyMis.IService {
public interface IServiceGetter:IDependency {
/// <summary>
/// IOC根据服务名取得服务
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serviceName"></param>
/// <returns></returns>
T GetServiceByName<T>(string serviceName);
}
}
/*
* IOC根据注册的名称取得对应的服务利用Autofac来实现
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyMis.IService;
using Autofac;
using Autofac.Integration.Mvc;
namespace MyMis.Service.AssertManage {
public class ServiceGetter:IServiceGetter {
public T GetServiceByName<T>(string serviceName) {
T _service = AutofacDependencyResolver.Current.RequestLifetimeScope.ResolveNamed<T>(serviceName);
return _service;
}
}
}
使用时直接如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMis.IService;
using MyMis.DTO;
using MyUtility;
using Newtonsoft.Json;
using MyMis.Controllers;
using System.Threading.Tasks;
using Autofac.Integration.Mvc;
using Autofac;
namespace MyMis.Web.Areas.Assets.Controllers
{
public class GeneralAssetsListController : Controller
{
private IServiceGetter _ServiceGetter;
private IAms_assetsService _service;
public GeneralAssetsListController(IServiceGetter ServiceGetter,) {
_ServiceGetter = ServiceGetter;
_GeneralAssetsService = GeneralAssetsService;
_service = _ServiceGetter.GetServiceByName<IAms_assetsService>("ProxyassetsService");
}
//
// GET: /Assets/GeneralAssetsList/
public ActionResult Index()
{
var r = _service.GetAssetsById("YJ19001");
return View();
}
}
}