遇到 这个 问题 找了很久不知道怎么结局呢,因为 A的构造函数 依赖别的 IB接口作为参数。
而IB接口又依赖另一个接口IC,IC 又依赖 ID。。。。
public class AutofacCfg { private IContainer Container; public AutofacCfg() { var container = ConfigureContainer(); //var application = container.Resolve(); Container = container; } private static IContainer ConfigureContainer() { var builder = new ContainerBuilder(); //var asms = Assembly.GetExecutingAssembly().GetReferencedAssemblies().ToList(); // asms.Where(asm => asm.FullName.StartsWith("Easy") || asm.FullName.EndsWith("xTest") || asm.FullName.EndsWith("BLL")); // Assembly.LoadFrom() var assemblys = AppDomain.CurrentDomain.GetAssemblies().Where( asm => asm.FullName.StartsWith("Easy") || asm.FullName.EndsWith("xTest") || asm.FullName.EndsWith("BLL")).ToArray(); builder.RegisterAssemblyTypes(assemblys) .Where(type => type.Name.EndsWith("Test") || type.Name.EndsWith("Service")).AsSelf() .AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope(); return builder.Build(); } public T Get<T>() { var iTypes = typeof(T).GetInterfaces(); if (iTypes.Count() == 0) { throw new NotImplementedException("依赖注入的类型没有实现接口"); } if (!Container.IsRegistered<T>()) { var builder = new ContainerBuilder(); //builder.RegisterType<T>().AsSelf() // .AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope(); RegisterServices<T>(builder, iTypes[0]); // Add the registrations to the container //.RegisterType<T>().UsingConstructor(typeof(ILogger), typeof(IConfigReader)); #pragma warning disable CS0618 builder.Update(Container); //,Autofac.Builder.ContainerBuildOptions.None); #pragma warning restore CS0618 } return Container.Resolve<T>(); } private static void RegisterServices<TService>(ContainerBuilder builder, Type iType) { builder.RegisterType<TService>().AsSelf().AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope(); }
调用处的代码:
autofacCfg = new AutofacCfg(); var test= autofacCfg.Get<IRequestManageServiceTest>(); test.Test(); //new IResumeManageServiceTest().RunTest(); //new IMailServiceTest().RunTest(); //Console.WriteLine(new ErrorEx("aaa").Message); //new DaoTest().Test(); Console.WriteLine("Hello World!"); Console.ReadLine();
IRequestManageServiceTest 的代码:
public class IRequestManageServiceTest: ITest { private IRequestManageService _IRequestManageService;
public IRequestManageServiceTest(IRequestManageService requestManageService) { _IRequestManageService = requestManageService; } public void Test() { var pagingInfo =new PagingInfo() { RowCount = 0, PageIndex = 0, PageSize = 0, OrderField = "" }; _IRequestManageService.GetRequestPositionsByStaffNo(pagingInfo,"0003"); Console.WriteLine("Test Func"); } } public interface ITest { }
问题在于 我始终获取不到
_IRequestManageService的值,始终为null。
请教 怎么解决
经过长时间的 尝试 终于解决问题了。解决问题的秘诀就是:
你要 提前加载 所有要用到的dll。
与此同时,public T Get<T>() 这个函数虽然可以注册一些显示调用的类型,但是 它 并不会更新它自身依赖的类型。(比如构造函数里面依赖另一个接口)。但是它并会去主动寻找那个接口的默认实现,更不会去注册它。因此构造函数注入就会失败。