/// <summary> /// 管理类 /// </summary> public partial class Mgr { private static IContainer container = null; /// <summary> /// 自定义容器和组件注册 /// </summary> /// <returns></returns> public static IContainer GetContainer() { if (container == null) { var builder = new ContainerBuilder(); //builder.RegisterType<SqlDatabase>().As<IDatabase>(); builder.RegisterType<SqlDatabase>().Named<IDatabase>("AutofacDemo.Lib.Sql.SqlDatabase"); builder.RegisterType<OracleDatabase>().Named<IDatabase>("AutofacDemo.Lib.Oracle.OracleDatabase"); container = builder.Build(); } return container; } }
<?xml version="1.0"?> <configuration> <configSections> <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/> </configSections> <autofac> <components> <component name="AutofacDemo.Lib.Oracle.OracleDatabase" type="AutofacDemo.Lib.Oracle.OracleDatabase, AutofacDemo.Lib.Oracle" service="AutofacDemo.Lib.IDatabase, AutofacDemo.Lib"/> <component name="AutofacDemo.Lib.Sql.SqlDatabase" type="AutofacDemo.Lib.Sql.SqlDatabase, AutofacDemo.Lib.Sql" service="AutofacDemo.Lib.IDatabase, AutofacDemo.Lib"/> </components> </autofac> <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
/// <summary> /// 根据配置文件里的服务名生成对象 /// </summary> public static void GetFrom_Config() { var builder = new ContainerBuilder(); //从.config配置文件中取得相关的组件注册 builder.RegisterModule(new ConfigurationSettingsReader("autofac")); using (var container = builder.Build()) { string vServiceName = "AutofacDemo.Lib.Oracle.OracleDatabase";//服务名 //vServiceName = "AutofacDemo.Lib.Sql.SqlDatabase"; //是否存在服务名 if (container != null) { if (container.IsRegisteredWithName(vServiceName, typeof(IDatabase))) { IDatabase db = container.ResolveNamed<IDatabase>(vServiceName); if (db != null) { db.Select(".........."); } } } } }
//是否存在服务名 if (container.IsRegisteredWithName(vServiceName, typeof(IDatabase))) { IDatabase db = container.ResolveNamed<IDatabase>(vServiceName); if (db != null) { db.Select(".........."); } }
点此下载
/// <summary> /// 自定义容器和通过反射进行组件注册 /// </summary> /// <returns></returns> public static IContainer GetContainer() { if (container == null) { var builder = new ContainerBuilder(); Type objType = Type.GetType("AutofacDemo.Lib.IDatabase, AutofacDemo.Lib"); Type objTypeA = Type.GetType("AutofacDemo.Lib.Oracle.OracleDatabase, AutofacDemo.Lib.Oracle"); Type objTypeB = Type.GetType("AutofacDemo.Lib.Sql.SqlDatabase, AutofacDemo.Lib.Sql"); builder.RegisterType(objTypeA).Named("AutofacDemo.Lib.Oracle.OracleDatabase", objType); builder.RegisterType(objTypeB).Named("AutofacDemo.Lib.Sql.SqlDatabase", objType); ////需要知道接口 //builder.RegisterType(objTypeA).Named<objType>("AutofacDemo.Lib.Sql.SqlDatabase"); //builder.RegisterType(objTypeB).Named<objType>("AutofacDemo.Lib.Oracle.OracleDatabase"); container = builder.Build(); } return container; }
download