Tag: simple injector

用Mock测试Nunit。 接口实例

我有以下(简化)代码。 public class Controller { private readonly IService _service; public Controller(IService service) { _service = service; } public async Task Create(MyObject object) { var result = _service.method(object); if (!result.Succeeded) { return this.GetErrorResult(object); } } } 和SimpleInjector用于注入_service和它的实现类之间的依赖关系,如下所示: public static void Register(Container container) { container.Register(); } 作为一个注释,注射和unit testing对我来说是新的,所以我不完全理解它们,但我正在学习。 如果我通过Swagger运行应用程序,一切正常。 注意,当我通过Swagger运行应用程序时,会调用Register函数。 现在,我正在尝试使用NUnit设置一些unit testing,并且像这样模拟IService对象: var Service = new Mock(); […]

RegisterWithContext和Lifestyle Mismatch

我想向我的控制器注入一个记录器,我需要将扩展​​信息传递给记录器的构造函数。 为此,我使用RegisterWithContext : container.RegisterWithContext(context => { if (context.ServiceType == null && !container.IsVerifying()) { throw new InvalidOperationException( “Can’t request ILogger directly from container, ” + “it must be injected as a dependency.”); } return new Common.Logging.NLogLogger(context.ImplementationType.FullName); }); RegisterWithContext扩展方法显式将提供的委托注册为Transient 。 我需要在一个恰好是单例的服务中注入相同的Logger( Common.Logging.NLogLogger )。 在升级到SimpleInjector 3.0.6之前,事情似乎按预期工作,而container.Verify()对整个配置非常满意。 升级后,validation程序返回一些错误: [Lifestyle Mismatch] SearchEngineIndexerService(Singleton)依赖于ILogger(Transient)。 [Lifestyle Mismatch] MembershipService(Web Request)取决于ILogger(Transient)。 这是有道理的。 我能理解为什么会发生这种情况以及为什么要避免它。 我试图避免“我是否记录太多”综合症,但实际上,我确实需要在一些服务中进行一些记录。 我已经尝试使用RegisterConditional根据某些条件注册一个不同的记录器,但是,当然,所有记录器现在应该是有条件注册的,否则我会得到这个exception: […]

如何在SimpleInjector 2.6.1+中unit testing开放的通用装饰器链

给定以下使用SimpleInjector的开放式通用deocrator链: container.RegisterManyForOpenGeneric(typeof(IHandleQuery), assemblies); container.RegisterDecorator( typeof(IHandleQuery), typeof(ValidateQueryDecorator) ); container.RegisterSingleDecorator( typeof(IHandleQuery), typeof(QueryLifetimeScopeDecorator) ); container.RegisterSingleDecorator( typeof(IHandleQuery), typeof(QueryNotNullDecorator) ); 使用SimpleInjector 2.4.0,我能够使用以下代码对此进行unit testing以断言装饰链: [Fact] public void RegistersIHandleQuery_UsingOpenGenerics_WithDecorationChain() { var instance = Container .GetInstance<IHandleQuery>(); InstanceProducer registration = Container.GetRegistration( typeof(IHandleQuery)); instance.ShouldNotBeNull(); registration.Registration.ImplementationType .ShouldEqual(typeof(HandleFakeQueryWithoutValidator)); registration.Registration.Lifestyle.ShouldEqual(Lifestyle.Transient); var decoratorChain = registration.GetRelationships() .Select(x => new { x.ImplementationType, x.Lifestyle, }) .Reverse().Distinct().ToArray(); decoratorChain.Length.ShouldEqual(3); decoratorChain[0].ImplementationType.ShouldEqual( typeof(QueryNotNullDecorator)); decoratorChain[0].Lifestyle.ShouldEqual(Lifestyle.Singleton); decoratorChain[1].ImplementationType.ShouldEqual( typeof(QueryLifetimeScopeDecorator)); […]

简单的注入器和使用Log4net的日志抽象

为了尝试使用Log4net获得一个很好的日志抽象,我从这个SOpost中获取了抽象,并从这个SOpost中获取了适配器,并尝试让它们一起工作。 真正剩下要做的就是配置容器,这是我没有成功的部分。 我试过的配置是 public static class InfrastructureRegistry { public static void RegisterLoggingServices(this Container container) { container.RegisterConditional(typeof(ILog), c => LogManager.GetLogger( c.Consumer.ImplementationType).GetType(), Lifestyle.Scoped, c => true); container.RegisterPerWebRequest(); } } 从代码中可以看出,我想要一个特定的log4net记录器,它从注入它的类中获取Type。 虽然大多数日志记录都是在一个包罗万象的情况下完成的,但我希望在较低层进行一些日志记录,例如在表单validation失败时。 我使用该配置获得的ActivationException是: LogImpl类型的构造函数包含名为“logger”的参数,并键入未注册的ILogger。 请确保ILogger已注册,或更改LogImpl的构造函数。 不太确定从哪里开始,所以任何帮助将不胜感激。 编辑 对不起,我应该指出我正在尝试编写它,以便我只需要编写一次此配置。 以下工厂function有效,但我不想每次要注入记录器时手动添加更多配置: container.RegisterPerWebRequest(() => LogManager.GetLogger(typeof(LoginController)));

在Simple Injector中Ninject WhenInjectedInto等效

映射到常量值。 例如,当您需要解析一个automapper IMapper实例时会发生这种情况,例如Ninject中的示例 var config = new MapperConfiguration( cfg => { cfg.AddProfile( new MyMapperConfiguration() ); } ); Bind().ToConstant( config ).InSingletonScope(); Bind().ToConstant( config.CreateMapper() ); 根据注入类型绑定不同的实现 当一组公共类依赖于公共接口但具体实现应该不同时,就会发生这种情况。 例 public interface ICardService {} public class TypeACardService : ICardService, ITypeACardService { public TypeACardService( ICardValidator validator ) { } } public class TypeBCardService : ICardService, ITypeBCardService { public TypeBCardService( ICardValidator […]

使用IoC链接层,将较低的回调设置为较高并避免循环引用

我有一个场景,我需要一个较低层由上层控制,就像一个木偶大师拉弦。 由于一些内部事件不时生成,因此下层也将回调上层。 我正在使用SimpleInjector,我将ILower注入到Upper构造函数中。 我不能将Upper注入Lower,因为它会导致循环引用。 相反,我有一个寄存器回调函数来链接这两个层。 但是,我必须使用空检查分散我的代码。 有没有更好的方法或不同的架构来实现这种对象的链接? // an interface that transport can callback from transport to client public interface ILowerToUpperCallback { void ReplyA(); void ReplyB(); } // transport interface that client calls public interface ILower { void Test1(); void Test2(); void RegisterCallback(ILowerToUpperCallback callback); } public class Upper : ILowerToUpperCallback { private readonly ILower lower; […]

多个RegisterAll注册使用与SimpleInjector相同的单例集

我正在使用Simple Injector为电子商务项目构建一个插件系统。 我正在使用RegisterAll来注册IPaymentProvider和IResourceRegistrar所有实现(以及更多)。 但这每次都会创建一个新实例。 建议在每种类型上使用RegisterSingle 。 但是在这种情况下如何实现这一目标呢? private static void RegisterMultipleUnderOneInterface( Container container, string name) { IEnumerable pluginRegistrations = from dll in finder.Assemblies from type in dll.GetExportedTypes() where type.GetInterfaces().Any(i => i.Name == name) where !type.IsAbstract where !type.IsGenericTypeDefinition select type; if (pluginRegistrations.Any()) { var @interface = pluginRegistrations.ElementAt(0).GetInterfaces() .First(i => i.Name == name); foreach (Type type in […]

Simple Injector将硬编码值传递给构造函数

在Simple Injector中,我可以执行以下操作: container.RegisterSingle(() => new AuctionContext( new Uri(“http://localhost:60001/AuctionDataService.svc/”))); 我在这里做的是说当找到IAuctionContext时,用这个新的AuctionContext替换它。 问题是,通过调用RegisterSingle ,只会使用一个AuctionContext实例。 我希望它能够传递如上所述的Uri参数但不具有单个实例但每次都允许新实例。 这怎么可能?

使用Simple Injector进行方法级别的属性拦截

使用Unity,我可以快速添加基于属性的拦截 public sealed class MyCacheAttribute : HandlerAttribute, ICallHandler { public override ICallHandler CreateHandler(IUnityContainer container) { return this; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { // grab from cache if I have it, otherwise call the intended method call.. } } 然后我这样注册Unity: container.RegisterType( new ContainerControlledLifetimeManager(), new Interceptor(), new InterceptionBehavior()); 在我的存储库代码中,我可以选择性地装饰要缓存的某些方法(具有可以为每个方法单独定制的属性值): [MyCache( Minutes = 5, CacheType […]

MassTransit和Simple Injector

我正在审查.NET的MassTransit分布式应用程序框架 。 根据网站MassTransit从一开始就建立了IoC容器的概念,并为少数更“主流”的IoC容器提供支持库。 (目前)有Nuofet包可用于Autofac,StructureMap,Castle Windsor,Ninject和Unity。 出于性能原因 ,我选择了Simple Injector作为我选择的IoC容器,但是我无法找到一个集成库,它将对Simple Injector的支持添加到MassTransit。 有没有人试过这个,让它工作,并有一些代码可以让我开始?