Dependency injection How do I set up Array/List dependencies in code with Castle Windsor?

I have the following classes: class Repository : IRepository class ReadOnlyRepository : Repository abstract class Command abstract CommandImpl : Command { public CommandImpl(Repository repository){} } class Service { public Service (Command[] commands){} } I register them in code as follows: var container = new Container("WindsorCOntainer.config"); var container = new WindsorContainer(new XmlInterpreter("WindsorConfig.xml")); container.Kernel.Resolver.AddSubResolver(new ArrayResol

Dependency injection Injecting HttpContext in Ninject 2

In my mvc application I'm using Ninject as a DI framework. My HttpAccountService is used by my controllers to get info from and to cookies. For this I need the HttpContext.Current in the HttpAccountService. As this is a dependency I injected it throught the constructor as such: kernel.Bind<IAccountService>() .To<HttpAccountService>() .InRequestScope() .WithConstructorArgument("context", HttpContext.Current); Sadly this always binds to the same context which ma

Dependency injection How to reuse a transient dependency in same context with Castle Windsor DI container

If I have the following setup, how can I configure my container to use the same database, when objects are created in the same context public class Database { } public interface IRepository { Database Database { get; } } public interface IFooRepository : IRepository { } public interface IBarRepository : IRepository { } public class FooRepository : IFooRepository { public Database Database { get; private set; } public FooRepository(Database database) { this.Database = database; } } pub

Dependency injection Injecting direct object dependencies, or methods directly as well

A best practice in DI I've read in a few places is not to inject object B just to get at object C, but to inject C instead. But if a single method from C is all that is required, would you just inject that method instead of C? If so, what about if a few methods from C were required? Is there a point that it's just more convenient to pass in the full object and live with the fact that you're getting stuff you have no interest in? Or does that point indicate that maybe class C has too many var

Dependency injection What's the purpose of the "container" in an "IoC container"?

Possible Duplicate: Arguments against Inversion of Control containers Using IoC (or Dependency Injection, DI) really helps in the creation of reusable components. DI also has benefits, it has been claimed, for testing your classes. But, what is the purpose of the container that IoC/DI alone doesn't already bring to the table? Since there is a cost involved it would be nice to be able to tell when that cost becomes justified.

Dependency injection Configure decorators with NServiceBus DI

How can I configure NServiceBus to inject decorated classes correctly? Imagine this scenario: public class A { public IDependency Dependency {get;set;} } public class B : IDependency { public IDependency DecoratedDependency {get; set;} } public class C : IDependency{} I want to set up my config so that B is created with C injected, and then A is created with B injected. I don't want A created with C injected. How do I set the config up so that it does this? It feels like I shoul

Dependency injection Abstract factories for injecting runtime dependencies in complex hierarchies

Given the following class hierarchy ClassA needs ClassB ClassB needs ClassC we get a dependency graph like this: ClassA --> ClassB --> ClassC so if we use DI we inject ClassC into ClassB and ClassB into ClassA. But now let's say ClassC is a runtime dependency (for example some kind of strategy). The proposed way to inject a runtime dependency is to introduce an abstract factory like a ClassCFactory Now we can inject ClassCFactory into ClassB and get the following graph ClassA

Dependency injection Can I pass other components into Castle Windsor config?

Lets say I have a main component that I want to initialize in a specific way and I have it's constructor take an Interface for this purpose. Is there a way to define the implementation I want for this interface in my xml and in turn inject that into the main component as a parameter? Like this: public interface IComponent2 { void DoStuff(); } public class ConcreteCompImpl2 : IComponent2 { IComponent1 _comp; public ConcreteCompImpl2(IComponent1 comp) { _comp = comp; }

Dependency injection How to configure Simple Injector depending on build configuration

I want to be able, to configure Simple Injector differently for each developer (for prototyping purposes for example). The default configuration should be hardcoded, of course. I have used Unity before, and there I was able to overwrite the hardcoded registrations by an XML configuration file. This config file was not under source control, and so other developers could overwrite the hardcoded registrations with their custom registrations without interfering with others. The developers should n

Dependency injection Angular2 Beta dependency injection

I have a NavBar Component which loads the QApi Service, the QApi Service loads the UserService, but I get the following error: EXCEPTION: No provider for UserService! (NavBarComponent -> QApi -> UserService) Either I simply don't get the concept of dependency injection, I made a stupid error, or this is just way to complicated compared to native development... Thanks for your help. Here my code: UserService: import {Injectable} from 'angular2/core'; //import {User} from '../data-sour

Dependency injection symfony 3 Argument 1 passed to [some service]::__construct() must be an instance of [something] instance of Doctrine\ORM\EntityRepository given

I am trying to create a service: <?php namespace AppBundle\Service; use AppBundle\Repository\GroupEntityRepositoryInterface; use AppBundle\Repository\GroupUserRepository; use AppBundle\Repository\GroupUserRepositoryInterface; use AppBundle\Entity\Group; use AppBundle\Repository\GroupRepository; class GroupUserService { private $groupRepository; private $groupUserRepository; /** * @param GroupRepositoryInterface $groupRepository * @param GroupUserRepositoryInterfa

Dependency injection Setting up dotnet core with RavenDB

I'm currently facing a problem with setting up RavenDB with dotnet core for multiple environments. In StartUp class I have configured Raven as a Singleton and used the IOptions pattern to bind the settings Raven to the RavenSettings object. public virtual void ConfigureServices(IServiceCollection services) { Services.AddMvc() //Add functionality to inject IOptions<T> services.AddOptions(); // App Settings services.Configure<RavenSettings>(Configuratio

Dependency injection Dependency injection in `ActionFiliter` vs. calling `Activator.CreateInstance()`

Requiring to sometimes use dependency injection in ActioFilter or other attributes running before or after an action API or result is inevitable. However, it is carried out through passing the type to be injected to the attribute using the typeof keyword. In order to simplify the case, when having various implementations for an interface, I have found it much simpler to manually instantiate the type than using the built-in dependency injection framework. For example: public TestAttribute: Attr

Dependency injection Registering a MediatR pipeline constrained PostProcessor using ASP.NET Core DI

Previously, we had the following pipeline setup working for auditlogging purposes public class AuditLogPostProcessor<TRequest, TResponse> : IRequestPostProcessor<TRequest, TResponse> where TRequest : IAuditLogRequest<TResponse> Where IAuditLogRequest implements IRequest public interface IAuditLogRequest<TResponse> : IRequest<TResponse> All and only the Commands that implement the IAuditLogRequest reached the AuditLogPostProcesso

Dependency injection Symfony autowire services failing because two services are based on the same class

I'm starting a new project using Symfony 3.3. I'm would like to use the new autoconfigure/autowiring features but I'm running into an "issue" I'm not sure how to solve. I have the following services definition coming from an external bundle: command_bus: class: Name\Space\To\MessageBusSupportingMiddleware ... event_bus: class: Name\Space\To\MessageBusSupportingMiddleware ... Both services are based on the same "MessageBusSupportingMiddleware" class but their intention is tot

Dependency injection Dependency injection in core

I have following code: public void ConfigureServices(IServiceCollection services) { ... services.AddScoped<IWsApiProvider, WsApiProvider>(); services.AddScoped<IApplicationUserRepository, ApplicationUserRepository>(); ... } WsApiProvider has following: public Guid SessionId { get; set; } public IWSocketProvider WsApi { get; set; } In Invoke method I'm updating these properties: public Task Invoke(HttpContext httpContext, IOptions<AppSettings&

Dependency injection How to implement DI using Unity on a class which has a constructor - mvc?

suppose i have a interface and class like this public interface ILienholderBusinessService { string GetCoverage(IList<PolicyVinRequest> InputList); } public class LienholderBusinessService : ILienholderBusinessService { public ILienholderPolicySearchDataService LienholderPolicySearchDataService { get; set; } public LienholderBusinessService(ILienholderPolicySearchDataService LienholderPolicySearchDataService ) { this.LienholderPo

Dependency injection Inject OSGi Services in a non-component class

Usually I have seen in OSGi development that one service binds to another service. However I am trying to inject an OSGi service in a non-service class. Scenario trying to achieve: I have implemented a MessageBusListener which is an OSGi service and binds to couple of more services like QueueExecutor etc. Now one of the tasks of the MessageBusListener is to create a FlowListener (non-service class) which would invoke the flows based on the message content. This FlowListener requires OSGi ser

Dependency injection Symfony 4 Service Injection Too Few Arguments

In my Symfony 4 project I've created a HelloBlock class in the /src/Blocks/Hello/HelloBlock.php file. Here's its constructor... public function __construct(EntityManagerInterface $entityManager) { $this->em = $entityManager; } And then in my services.yaml I've added this... App\Blocks\: resource: '../src/Blocks' tags: ['controller.service_arguments'] When running my code (dev environment, cache cleared, etc) I'm getting the "Too few arguments" error. It's not in

Dependency injection 'REQUEST' object always undefined in NestJS dynamic module

I create some dynamic module(log.module.ts) @Global() @Module({}) export class LoggerModule { public static forRoot(options: WinstonModuleOptions = null): DynamicModule { const providers = createWinstonProviders(options); return { module: LoggerModule, providers: providers, exports: providers, }; } } And provider(log.provider.ts) export function createWinstonProviders(loggerOpts:WinstonModuleOptions): Provider[] { return [ { provide: 'logger', useFactory: () =&

Dependency injection No effect at applying of ON_CALL on a gmock object

For some fun purposes, I'm writing a Tetris game. I created two classes: "GameBackground" and "Tetromino". Since the "Tetromino" class has a dependency on the "GameBackground" class, I injected this dependency in the constructor using an interface such that I can test the "Tetromino" class independent of the GameBackground class by mocking it. When I use gmock to create the "GameBackgroundMock", the test fails. When I use my own mock li

Dependency injection ServiceStack IOC. AutoWire(this) tries to inject public properties that are not registered in the Container

When using ServiceStack and its IoC/DI framework, I have the following problem: The DI framework injects null into a property, and that property type is not registered in the Container. class DependencyInjectedA : IDependencyInjectedA { public DependencyInjectedB { get; set; } } class DependencyInjectedB { public Dictionary<DateTime, SomeClass> MyProperty { get; set; } } And in my Configure method: public override void Configure(Container container) { base.Configure(); // he

Dependency injection I'm confused about interface abstractions when using IoC

I've recently been trying to learn IoC, and have a couple questions based on the following code: public class WarriorModule : NinjectModule { public override void Load() { Bind<IWeapon>().To<Sword>(); Bind<Samurai>().ToSelf(); } } I'm having trouble grasping the new concept of interfaces. Before I would create an interface such as IRunnable, implementing the function void Run(). With IoC, I'm now viewing an interface as something that only m

Dependency injection Why so many terms to say the same thing? IoC and DIP

IoC = Inversion Of Control DIP = Dependency Inversion Principle (D in S.O.L.I.D.) IoC == DIP? I think so, is true. The world of building software is already so messy, why so many words to say the same thing? (I know DI (Dependency Injection) and it is different of DIP and IoC) Update: According to the answers, then we can say that: (DI) + (IoC) = (Dependency Inversion Principle) ?

Dependency injection Why inject dependencies?

Assuming I'm using an IoC container, why exactly must my types have their dependencies injected? Why can't every type just assume that the container exists and just retrieve the dependencies it needs for itself? What are the disadvantages to this latter approach? I'm aware of property injection but I don't want that suggested as an answer even though it does save on having long parameter list constructors in more complex types. And this doesn't save on the code you ultimately need to type/ma

Dependency injection When to use PerThreadLifetimeManager?

I am following the example linked to below for setting up unity to work with my service layer. My project is setup very similar to the one in this article and I understand everything except why exactly is PerThreadLifetimeManager used when registering the service dependency. Keep in mind I am also using a generic repository and unit of work that is being used in my service layer as well. Most unity examples use the default (transient) lifetime manager, and since my setup is similar to the one be

Dependency injection MVC5 Identity 2.0 Dependency Injection with Unity

I'm having trouble with Unity while trying to use DI with Identity 2.0. My project is MVC5 Wep Api2 REST services and AngularJS. That's what I've tried so far: (note that: MyExtendedGroup : IdentityRole) .RegisterType<MySecurityContext>("MySecurityCtx", new PerResolveLifetimeManager()) .RegisterType<IRoleStore<MyExtendedGroup, string>, RoleStore<MyExtendedGroup, string, IdentityUserRole>>("MyRolesStore", new InjectionConstructor(new ResolvedParameter<MySecurityContex

Dependency injection Ninject Owin Context Injection

I've develop a multi tier project with MVC5. And i use ASP.NET Identity 2.0.. And i use Ninject for depency injection. But i can't figure out how can i set call service layer in my controller. I use call directly call my manager class. public class UserController : Controller { private IUserService _userService; //i can't use this property at the moment. Because i can't iject it private UserManager _userManager; public UserManager UserManager { get {

Dependency injection How to peek at message while dependencies are being built?

I building multitenancy into the unit of work for a set of services. I want to keep the tenancy question out of the way of day-to-day business domain work, and I do not want to touch every existing consumer in the system (I am retrofitting the multitenancy onto a system without any prior concept of a tenant). Most messages in the system will be contexted by a tenant. However, there will be some infrastructure messages which will not be, particularly for the purpose of automating tenant creation

Dependency injection What's the equivalent of the DictionaryAdapterFactory of Windsor in Ninject?

I'm trying to reproduce the below configuration of Windsor on Ninject. I know ninject has a factory extension but it's far away from the dictionary adapter that windsor have. WindsorContainer container = new WindsorContainer(); container.AddFacility<Castle.Facilities.FactorySupport.FactorySupportFacility>(); container.Register( Component.For<IApplicationSettings>().UsingFactoryMethod( () => new DictionaryAdapterFactory() .GetAdapter<IApplicationSettings>(Confi

Dependency injection Microsoft.Framework.DependencyInjection: Adding services inside a scope

I started looking into Microsoft.Framework.DependencyInjection / Microsoft.Extensions.DependencyInjection (renamed post-beta 8) for usage in my own framework based on the MVC-paradigm. For this I per request have 3 scoped levels in which I'm trying to use the new Microsoft DI. A shared root scope for my the entire application, a nested scope for every controller and a further nested scope for every view. Even though this scoping works for resolving services from the root, I have no idea on how

Dependency injection Using Angular2 outside of browser

I am looking to build an Angular2 application that can be run in 2 different ways - either within Electron or via the CLI. Basically the underlying components of the application is a set of services. In the Electron version of the application these services will be exposed via a set of interactive components, however, for the CLI version they will be accessible using node. At the moment, I am in the research/PoC phase - trying to confirm that this is possible and 2 questions have arisen: Doe

Dependency injection Creating objects with AssistedInject Factory in Guice

I have a class that should be injected in two different ways: for general purpose as singleton customized version as RequestScoped. Example: public class TaskProcessorService implements TaskProcessor { private final TaskRegistry taskRegistry; @Inject public TaskProcessorService(TaskRegistry taskRegistry){ this(taskRegistry, null); } @AssistedInject public TaskProcessorService(TaskRegistry taskRegistry, @Assisted String userId) {...} public synchronized v

Dependency injection IDisposable implementation when container is guaranteed to call Dispose method

I have built a API service using ASP.NET Core. Just like any other API, this one has to retrieve some data from database, apply some business logic and then send data back to the client. To start with, I have EmployeeDataContext class that is scaffolded using Entity Framework.Core. This class is derived from Microsoft.EntityFrameworkCore.DbContext as shown below. public partial class EmployeeDataContext : DataContext { protected override void OnModelCreating(ModelBuilder modelBuilder)

Dependency injection TYPO3: What does dependency injection actually do and why do i need the following code?

A little question to understand TYPO3 better: In my controller i have following code: /** * applianceRepository * * @var \Cjk\Icingaconfgen\Domain\Repository\ApplianceRepository * * @inject */ protected $applianceRepository = null; It's about this whole dependency injection... Is it correct to assume that the injection fetches the dependencies from my TCA file for that specific class? Or what does the dependency injection actually do? From what i understan

Dependency injection Spring DI (Beans) with multiple concretes…picking one of them

I have a similar question here Guice with multiple concretes......picking one of them with a solution for Guice. But I have a different project using spring di (beans), but with the same kind of issue. I have an interface with N number of concretes. (3 here) public interface OrderProcessorInterface { void ProcessOrder(String preferredShipperAbbreviation, Order ord); } public class FedExShipper implements ShipperInterface { private Log logger; public FedExShipper(Log lgr) {

Dependency injection Can I configure Cayenne to use a provider to get a new instance of a model?

I'd like to provide constructor arguments via Guice to new Cayenne data objects, but it looks like cayenne just uses Class.newInstance() to instantiate new instances. Is there any way to have Cayenne use a provider to get a new instance instead? I'd need it to do this, for instance, when instantiating new instances during a fetch not just when I create a new instance. To expand a little, I have a Maven project that has all the Cayenne models and core business logic. Then I have another Maven pr

Dependency injection What are the requirements for Dependency injection in MVC 4 via Ninject?

I tried to inject dependencies into a controller's constructor, as i have previously. The problem is that i can't seem to get it to work. Is there any new requirement when doing DI with MVC 4 or am i missing some basic requirement ? I'm using: Ninject.MVC3 System.Web.MVC Here are the important sections for that matter: NinjectWebCommon.cs public static class NinjectWebCommon{ private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summar

Dependency injection In Dependency Injection where is an object to be injected created?

If it was created by the class that is injecting it into the object that uses it then isn't it just moving object creation one step up the stack? And wouldn't this mean that all objects needed by lower level classes would need to be passed through each object one at a time until it reached the object that needed it? All objects and their dependencies could be set up at the very beginning, but wouldn't this dent performance as objects will be hanging around until needed?

Dependency injection PHP Dependency Injection - magic methods injections?

I'm trying to get my head around DI. Am I doing it correctly for classes that follow DI pattern? class Boo { public $title = 'Mr'; public $name = 'John'; protected $deps; public function __construct($deps) { $this->deps = $deps; } public function methodBoo() { return 'Boo method '.$this->deps; } } class Foo { private $objects; public function __construct() { } // Set the inaccessible property magically. pub

Dependency injection PicoContainer JSR-330 @Named support?

PicoContainer seems to indicate that it supports JSR-330 @Inject and @Named. (No, this other question doesn't seem to help, as it doesn't address the fact that the PicoContainer site says that some support for JSR-330 has been added.) I add something to the container like this: container.addComponent(Foo.class); container.addComponent("myBar", new MySpecialBar()); container.addComponent("decoy", new SomeOtherBar()); I mark constructor parameters with @Named: public class Foo(@Named("myBar")

Dependency injection How do I perform constructor injection with an NServiceBus saga?

If I have a class HelperClass that I'd like to use within a saga, I'd like to be able to inject an IHelperClass into the constructor. The problem I'm running into is that sagas appear to be instantiated with an empty constructor; so while I can create a constructor that takes IHelperClass and use it in unit tests, the framework will always call the parameterless constructor. I think I could use property injection, but since this helper class is "necessary," my understanding is that property in

Dependency injection How to use .net core dependency injection in multiprojects solution?

I'm new to core. What I'm trying to do is to build multi projects solution and use dependency injection to pass interfaces between projects. What I know is that in ASP.NET core project we have ConfigureServices method in startup.cs file to register our interfaces and their implementations like this: public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddTransient<IMyInterface,MyImplementation>(); .....

Dependency injection .net core 2.0 change injected middleware settings at runtime

Hope my question will be clear. ;-) Is it possible to change Middleware settings during runtime? I explain more. I have following code in my configure services method in an core 2.1 webapi services.AddMvc(options => if (!securitySettings) { options.Filters.Add(new AllowAnonymousFilter()); } I would like to add that filter depending on a setting in the database. Is it possible to change that during runtime or do i re

Dependency injection In NestJS, how do you inject Dynamic modules async options to module internal imports?

In Nestjs if I have a Dynamic Module A that accepts an options object as per forRootAsync logic, how do I inject that options to its imported modules? (lest's say module A imports module B which depends on some of Module A options) I know how to inject the options object to modules A providers but how do you inject it to Module A imported modules? note: to inject the options to module A imported providers I can wrap the options object using a value provider and use the inject capabilities of

  1    2   3   4   5   6  ... 下一页 最后一页 共 9 页