Tag: 简单注入器

SimpleInjector针对每个Web请求和生命周期范围混合生活方式

我使用Simple Injector作为我的IoC容器,并使用以下技术为每个Web请求或每个线程注册某些对象的“混合”生活方式。 interface IUnitOfWork { } interface IWebUnitOfWork : IUnitOfWork { } interface IThreadUnitOfWork : IUnitOfWork { } class UnitOfWork : IWebUnitOfWork, IThreadUnitOfWork { } container.RegisterPerWebRequest(); container.RegisterLifetimeScope(); container.Register(() => container.GetInstance()); // Register as hybrid PerWebRequest / PerLifetimeScope. container.Register(() => { if (HttpContext.Current != null) return container.GetInstance() as UnitOfWork; else return container.GetInstance() as UnitOfWork; }); 我对这个解决方案并不完全满意,因为每个要求我必须定义额外的空接口以使其工作并确保它们由我的具体类引用。 […]

container.RegisterWebApiControllers(GlobalConfiguration.Configuration)导致InvalidOperationException

在我的集成测试中,我使用的是我正在测试的Web API项目中构建的相同的SimpleInjector.Container。 但是这一行在组合根类中: container.RegisterWebApiControllers(GlobalConfiguration.Configuration); 导致exception: System.TypeInitializationException : The type initializer for ‘MyProject.Api.Test.Integration.HttpClientFactory’ threw an exception. —- System.InvalidOperationException : This method cannot be called during the application’s pre-start initialization phase. Result StackTrace: at MyProject.Api.Test.Integration.HttpClientFactory.Create() at MyProject.Api.Test.Integration.Controllers.ProductControllerIntegrationTest.d__0.MoveNext() in d:\Projects\My\MyProject.Api.Test.Integration\Controllers\ProductControllerIntegrationTest.cs:line 26 —– Inner Stack Trace —– at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() at System.Web.Compilation.BuildManager.GetReferencedAssemblies() at System.Web.Http.WebHost.WebHostAssembliesResolver.System.Web.Http.Dispatcher.IAssembliesResolver.GetAssemblies() at System.Web.Http.Dispatcher.DefaultHttpControllerTypeResolver.GetControllerTypes(IAssembliesResolver assembliesResolver) at System.Web.Http.WebHost.WebHostHttpControllerTypeResolver.GetControllerTypes(IAssembliesResolver assembliesResolver) […]

简单的注射器条件注射

假设我有两个控制器:ControllerA和ControllerB。 这两个控制器都接受参数IFooInterface。 现在我有2个IFooInterface,FooA和FooB的实现。 我想在ControllerA中注入FooA,在ControllerB中注入FooB。 这很容易在Ninject中实现,但由于性能更好,我正在转向Simple Injector。 那么我怎样才能在Simple Injector中做到这一点? 请注意,ControllerA和ControllerB驻留在不同的程序集中并动态加载。 谢谢

Simple Injector – 使用相同generics类型的另一个依赖项注册装饰器

我想我在Simple Injector的RegisterDecorator()偶然发现了一个怪癖。 它甚至出现在最近的2.5.0中。 我有一种情况,我想装饰一个封闭的generics类型,例如ICommandHandler ,一个装饰器(通过构造函数注入)一个类型为ICommandHandler的内部处理程序,还有另一种类型的处理程序,比如ICommandHandler 。 尽管这些命令处理程序类型是不同的,但是当我在这样的装饰器类型上调用RegisterDecorator时,SimpleInjector似乎会混淆并引发exception: ArgumentException:为了使容器能够使用MessageLogger作为装饰器,其构造函数必须包含ICommandHandler类型的单个参数(或Func<ICommandHandler> ) – 即正在装饰的实例的类型。 参数类型ICommandHandler在类MessageLogger的构造函数中定义多次。 …即使装饰器显然只有一个ICommandHandler参数。 以下是抛出exception的完整工作示例: public interface ICommandHandler { void Execute(T command); } public class LogCommand { public string LogMessage { get; set; } public DateTime Time { get; set; } } public class Logger : ICommandHandler { public void Execute(LogCommand command) { Debug.WriteLine(string.Format(“Message \”{0}\” sent […]

如何使用dependency injection从多个源获取配置?

我正在使用Simple Injector,但也许我需要的更多是一个概念性的答案。 这是交易,假设我有一个界面与我的应用程序设置: public interface IApplicationSettings { bool EnableLogging { get; } bool CopyLocal { get; } string ServerName { get; } } 然后,通常会有一个实现IApplicationSettings的类,从指定的源获取每个字段,例如: public class AppConfigSettings : IApplicationSettings { private bool? enableLogging; public bool EnableLogging { get { if (enableLogging == null) { enableLogging = Convert.ToBoolean(ConfigurationManager.AppSettings[“EnableLogging”]; } return enableLogging; } } … } 然而! […]

Simple Injector:在同一个图的服务中注入相同的UnitOfWork实例

我有多个服务,每个服务都使用Simple Injector IoC容器将UnitOfWork注入到构造函数中。 目前我可以看到每个UnitOfWork实例都是一个单独的对象,这很糟糕,因为我使用的是Entity Framework,并且需要在所有工作单元中使用相同的上下文引用。 如何确保每个解析请求将相同的UnitOfWork实例注入到所有服务中? 命令完成后,我的UnitOfWor将由外部命令处理程序装饰器保存。 请注意,这是一个通用库,将用于MVC和Windows Forms,如果可能的话,为两个平台提供通用解决方案会很不错。 代码如下: // snippet of code that registers types void RegisterTypes() { // register general unit of work class for use by majority of service layers container.Register(); // provide a factory for singleton classes to create their own units of work // at will container.RegisterSingle(); // register […]

无法使用Simple Injector注册Api控制器?

我有一个使用Simple Injector的WebApi,它工作得非常好,但我必须在项目中实现OAuth。 现在我已经这样做了,我的ApiControllers给了我一个像Simple Injector这样的错误,现在已经正确设置了 我有我的Start.cs文件 public class Startup { public void Configuration(IAppBuilder app) { // Web API configuration and services HttpConfiguration config = new HttpConfiguration(); Container container = SimpleInjectorConfig.Initialize(app); ConfigureAuth(app, container); WebApiConfig.Register(config); app.UseWebApi(config); } public void ConfigureAuth(IAppBuilder app, Container container) { var OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString(“/token”), AccessTokenExpireTimeSpan […]

注册具有相同接口但不同构造函数参数的多个单例

我有2个存储(Azure)帐户让我们调用它们src和dest我有控制器需要访问这两个,我正在尝试找出如何有条件地注册这2个单身。 这个答案给了我一些希望,但我不能完全解决,我想做的是(感谢RegisterSingletonConditional不是一个有效的fn): IBlobAccessClient src = new BlobAccessClient(srcConnectionString); IBlobAccessClient dest = new BlobAccessClient(destConnectionString); container.RegisterSingletonConditional( src, c => c.Consumer.Target.Parameter.Name.Contains(“src”)); container.RegisterSingletonConditional( dest, c => c.Consumer.Target.Parameter.Name.Contains(“dest”)); 任何指导赞赏。

如何使用Simple Injector在ASP.NET HttpModule中正确地注入构造函数/属性

我有一个名为UsersOnlineModule的类,它是从IHttpModul创建的。 在这个类中,我希望注入两个属性,我正在使用Simple Injector 。 public class UsersOnlineModule { public ITenantStore tenantStore; public ICacheManager cm; 我从IHttpModule调用这个类: Modules.UsersOnline.UsersOnlineModule usersOnlineModule = new Modules.UsersOnline.UsersOnlineModule(); usersOnlineModule.TrackUser(app.Context); 但是我的IHttpModule不了解缓存管理器或tenantStore 。 我可以通过从容器中获取对象来解决这个问题,但是我不想创建对Simple Injector的引用。 有没有其他不错的选择来解决这两个属性而不创建对我的容器的引用? – 更新 我修改了这个例子如下: class ImportAttributePropertySelectionBehavior : IPropertySelectionBehavior { public bool SelectProperty(Type serviceType, PropertyInfo propertyInfo) { return typeof(IHttpModule).IsAssignableFrom(serviceType) && propertyInfo.GetCustomAttributes().Any(); } } private static void RegisterHttpModules(Container container) { var httpModules […]

动作filter上的简单注入属性注入

我要注入的动作filter就像这样开始 public class UserAuthorisation : AuthorizeAttribute { public IWcfClientProxy FrameworkServiceProxy { get; set; } 我已经像这样设置了我的容器: container.Register<IWcfClientProxy>( ()=> new WcfClientProxy()); container.RegisterInitializer(handler => { handler.FrameworkServiceProxy = container .GetInstance<IWcfClientProxy>(); }); 当我运行它时, FrameworkServiceProxy属性为null。 我读过这篇文章: Simple Injector:在基类中注入一个属性并按照答案。 我还在本页简单注射器文档中阅读了示例。 我不是注入基类,也许这就是问题所在? ##更新## 我正在添加更多信息,因为我认为它应该是根据史蒂文斯的回答所说的。 我正在使用NuGet包用于MVC 3.这将以下内容添加到应用程序中: public static class SimpleInjectorInitializer { /// Initialize the container and register it as MVC3 Dependency Resolver. public […]