FAQ Database Discussion Community


Get instances using runtime data in Simple Injector

c#,architecture,dependency-injection,inversion-of-control,simple-injector
I have an application which builds its user-interface based upon a user configuration in a database. I have created an interface called IAction which looks like this; public interface IAction { ActionType ActionType { get; } bool CanExecute { get; } void Configure(ActionConfigDto config); void Execute(); } An implementation such...

StructureMap and objects not setup for DI/IoC

c#,dependency-injection,inversion-of-control,structuremap3
I have a situation where I've created a factory method to create an object. However, the object has boilerplate code that needs execution before the object is created. Fixing that part of the design is out of scope for this question. Also, when the object is created, a status display...

IOC containers: de-duplicating the configuration code

java,spring,oop,design-patterns,inversion-of-control
I am using spring framework for 2 different applications. Let's say both of the applications talk to one single MongoDB database. Following is how I configure MongoDB in both the applications: @Configuration @PropertySource("file:/etc/x/y/mongodb.properties") public class MongoConfiguration { @Autowired private Environment env; @Bean public UserCredentials mongoCredentials() { String mongoUserName = env.getProperty("mongodb.username");...

Laravel ServiceContainer and Facade (beginner)

php,laravel,inversion-of-control
Firs time using the IOC and Facades. I'm trying to make a "teamleader" facade so that I can call Teamleader::getCompaniesByCountry(); And I'm getting the error Non-static method Notflip\Teamleader\Teamleader::getCompaniesByCountry() should not be called statically, assuming $this from incompatible context This is my ServiceProvider <?php namespace Notflip\Teamleader; use Illuminate\Support\ServiceProvider; class TeamleaderServiceProvider extends...

Unity ResolveAll not working

c#,dependency-injection,inversion-of-control,unity
I am using Unity for the first time. I am trying to add some dependencies in code, but they are not getting resolved. Code below: public interface IClassA { void Show(); void ShowCount(); int ID { get; set; } } class ClassA : IClassA { public int count = 0;...

Is HierarchicalLifetimeManager the correct lifetime manager to use for WCF client / ChannelFactory

wcf,dependency-injection,inversion-of-control,unity,object-lifetime
I have a very simple WPF application that is calling There is one container for the application, that is configured when the application starts. The WPF app has a service reference to my WCF service. I have registered my generated proxy to the container like this: container.RegisterType<IAccountService>( new HierarchicalLifetimeManager(), new...

MVVM Light Messenger and Dynamic Dll Messages not received

c#,wpf,inversion-of-control,mvvm-light
I'm working on a WPF project where we are using MVVM Light Messenger and SimpleIOC. The solution has several projects that provide implementations for working with Serial / USB devices, and those implementations use a common interface to abstract away the details of the various devices. At application startup, the...

Unity resolve using type from derived class

c#,inversion-of-control,unity
I am trying to setup a structure where I have two sets of derived classes (models and views) implementing a common interface, and I want to use Unity to allow me to create/resolve a view from a model instance. E.g., public interface ICommonA {} public class ModelA : ICommonA {}...

What's the principle to define an interface with dependencies?

java,design,inversion-of-control,method-signature
Which dependency should locate in a method signature as a param and which should not? Since we have IoC container like spring, most of the dependencies could get injected through it. For java.util.concurrent.Executor: public interface Executor { void execute(Runnable command); } The interface could be public interface Executor { void...

Are “Dependency Injection Container” and “Inversion of Control Container” one and the same thing?

dependency-injection,inversion-of-control,ioc-container
In many articles i read about Dependency Injection Container, and many others talk about IoC Container. And while there must be some places that mention both, i have not come across one yet. So the question is: What is the relationship between these two? Are they the same thing? or...

Dynamic menu creation IoC

c#,inversion-of-control,autofac,ioc-container
I am wondering if anyone out there knows how I could create how could i use something like AutoFac to let me dynamically allow dll's to create there own forms and menu items to call them at run time. So if I have an, Employee.dll New Starter Form Certificate Form...

How do I bind generic types with inheritance using custom logic?

dependency-injection,ninject,inversion-of-control
I have a generic interface IService which is concretely implemented by three or four implementations. public interface IService { void HandleRequest( RequestData data ); } public class AService : IService { public void HandleRequest( RequestData data ) { } } public class BService : IService { public void HandleRequest( RequestData...

Laravel 5 IoC type-hinting not working

php,laravel,inversion-of-control,laravel-5
As far as I've understood, I should be able to type-hint my class instance arguments in the constructor of my class that I only instantiate with help of a Service Provider. Unfortunately I'm getting an error about missing arguments. Tracker.php function __construct($query, Tracker\Shipment $shipment) { $this->query = $query; $this->shipment =...

How to avoid retrieving a Spring managed bean from the context

spring,dependency-injection,apache-camel,inversion-of-control
My application receives messages, extracts data and persists the extracted data to a database. Data is received via a Apache Camel channel, added to a FIFO. The following code takes the next message from the FIFO and processes it. However, in order to do this it needs to get a...

Dependency injection + full virtual vs interfaces

c++,tdd,inversion-of-control,solid-principles
I quite often find myself creating interfaces that I am using just at the signature to inject a dependency, ending up with class AIface and class AImpl : public AIface. And quite often I never implement any other subclass of class AIface Is there any advantage of this approach vs...

NUnit keeps running the wrong version of a .dll

c#,nunit,inversion-of-control,castle-windsor,nlog
I am using the NUnit 2.6.4 test runner. I am running from an .nunit project file that loads my .csproj test. It keeps running the wrong version of a dependency. Background: I have castle windsor 3.3 using the NLog facility. I am using NLog 3.2. By default Windsor tries to...

Domain Events without Service Location

c#,domain-driven-design,ninject,inversion-of-control
Giving the default implementation of Domain Events: Interface that represents an domain event: public interface IDomainEvent { } Interface that represents a generic domain event handler: public interface IEventHandler<T> where T : IDomainEvent Central access point to raise new events: public static class DomainEvents { public static void Raise<T>(T event)...

Applying IoC design in library with multiple entry points

c#,.net,dependency-injection,inversion-of-control,ioc-container
I'm creating NuGet package which will allow its consumers to easily send/receive messages from Azure topics/queues (plus some specific for my needs additional logic). Package internal structure is pretty complicated with a lot of dependencies and is planned to be covered with unit tests, thus there was a decision to...

Retrofit unit tests to large solution, IOC, Moq

c#,vb.net,unit-testing,dependency-injection,inversion-of-control
I am in the process of retrofitting unit tests for a asp.net solution written in VB.Net and c#. The unit tests need to verify the current functionality and act as a check for future breaking changes. The solution comprises of: 1 MVC web project written in vb.net (don't ask, it's...

Simple Injector Register All Services From Namespace

c#,asp.net-mvc,inversion-of-control,ioc-container,simple-injector
My Service Interfaces has a namespace of Services.Interfaces The implementation of the Service Interfaces has a namespace of Web.UI.Services I have 2 service implementations for example IUserService which needs to register to UserService ICountryService which needs to register to CountryService This is how I currently register these services with SimpleInjector....

ServiceStack Funq Container setting public Members to null

c#,servicestack,inversion-of-control,funq
Some members of our devteam just spent some time debugging a similar issue. A RegisterAs class used in one of our unittests has a public member: public List Mails { get; set; } When this class is resolved through Funq, the member is set to null, even though it is...

Autofac registering all subtypes keyed according to a property

inversion-of-control,autofac
The following scenario: public enum ChildType { Type1, Type2, Type3 } public abstract class MyParentClass { public abstract ChildType Id { get; } } public class Child1 : MyParentClass { public override ChildType Id { get { return ChildType.Type1; } } } public class Child2 : MyParentClass { public override...

How to inject different instance(s) for different context in ASP.NET MVC using StructureMap?

asp.net,asp.net-mvc,inversion-of-control,structuremap
We are using classes inheriting from Registry to configure our StructureMap container in our ASP.NET MVC 4 application startup. Some excerpt from one of the registry-classes: For<ISomeInterface>().HybridHttpOrThreadLocalScoped().Use<SomeImplementation>(); We would like use different instances of our interfaces depending on the context. (For example switching from database "online" mode to "maintenance" mode...

How do I intercept Castle Windsor's component resolution to override dependencies?

c#,dependency-injection,inversion-of-control,castle-windsor
I'm looking for a way to hook into Castle Windsor's resolution process so that I can do something like: if (componentCanBeResolvedElsewhere) { return elsewhere.Resolve<TService>(); } else { windsorContainer.Resolve<TService>(); } I want Castle Windsor to handle the majority of my dependencies, but I want to provide an ability to 'fill-in the...

Decorators in Unity with many arguments

c#,.net,asp.net-web-api,inversion-of-control,unity
I have the following problem. I have two classes T1 and T2 that both implement interface T. I'd like T2 to decorate T1 so when I create an instance of T T2 is called first, then T1. public class T1 : IT { public void Call() { Write("T1"); } }...

Castle Windsor & Command Pattern

c#,dependency-injection,inversion-of-control,castle-windsor
I am trying to implement a Command, CommandHandler and CommandDispatcher pattern using Castle Windsor without manually asking the container to resolve a CommandHandler based on Command type (which is generally considered an anti-pattern). I found this old article, but the implementation of ITypedFactoryComponentSelector has changed, so now it returns a...

Autofac Generic Multiple Interface

c#,dependency-injection,domain-driven-design,inversion-of-control,autofac
I am trying to resolve one generic interface something like below but I am getting exception when trying to run the application . public interface IHandler<in T> where T : IDomainEvent { void Handle(T args); } public class ApplicationUserCreatedEventHandler : IHandler<ApplicationUserCreatedEvent> { public void Handle(ApplicationUserCreatedEvent args) { if (args ==...

How to pass a function to another class using IoC

c#,inversion-of-control,mef,ioc-container
I am trying to implement inversion of control (IoC) in order to develop a plug-in based application, which needs to be able to pass data (e.g. strings) back to my main EXE when something happens. To achieve this, I am passing an Action to the DLL which it can use...

FluentValidation in Lightinject

c#,model-view-controller,inversion-of-control,fluentvalidation,light-inject
I'm using fluentvalidation and lightinject Here is my code to insert a blog article; public OperationResultDto Add(BlogArticleDto blogArticleDto) { OperationResultDto result = new OperationResultDto(); ValidationResult validationResult = _blogArticleModelValidator.Validate(blogArticleDto); if (!validationResult.IsValid) { result.IsOk = false; ValidationFailure firstValidationFailer = validationResult.Errors.FirstOrDefault(); if (firstValidationFailer != null) { result.Message = firstValidationFailer.ErrorMessage; } return result; }...

Service Providers and IoC in Laravel

php,laravel,inversion-of-control,service-provider
I am going through the tutorial here, and I've run accross the following block of code in the ServiceProvider. public function register() { $this->app->bind("chat.emitter", function () { return new EventEmitter(); }); $this->app->bind("chat.chat", function () { return new Chat($this->app->make("chat.emitter")); }); $this->app->bind("chat.user", function () { return new User(); }); $this->app->bind("chat.command.serve", function ()...

Convert a class to a possible interface

c#,design-patterns,reflection,interface,inversion-of-control
I have two Interfaces in different projects (these projects are not referenced to each other) which have the same methods like this: In first project we have: public interface IInterfaceA { IAViewModel Do(); } public interface IAViewModel { int Id { get; set; } } public class ServiceA : IInterfaceA...

Autofac Resolve using delegate factory by type

c#,inversion-of-control,autofac
I am using Autofac for IoC in my project. Due to some legacy software libraries I must pass some services to the controller that can't be resolved, and must be passed as parameter. I've made a generic control using delegate factories like this: public MyClass<TController, TInterface> { private delegate TController...

How to update registered instances in Autofac container in runtime

c#,asp.net-mvc,dependency-injection,inversion-of-control,autofac
I want to replace existing registered instances in Autofac with new ones in ASP.NET MVC application in runtime. Registrations are keyed as I work with collections of instances of different subtype, though it seems to be irrelevant to my issue. Initial registration on application startup foreach (var instance in instances)...

Read Autofac xml configuration from DB and change it runtime

xml,configuration,inversion-of-control,autofac,code-injection
i'm having trouble searching for documentation and example reguarding autofac so i ask this here: i need to change at runtime the xml configuration that autofac accept to inject the implementations. I've thinked a scenario like this: a db field that is maintained and that decide how to configure Autofac....

Use one instance in multiple components with Autofac

c#,asp.net-mvc,entity-framework,inversion-of-control,autofac
So I have an IApplicationDbContext class and an ApplicationDbContext class that implements it. In the code written by me I use IApplicationDbContext, but higher up on the chain MVC uses ApplicationDbContext and I can't really change that, so at the moment I have registered components like this: builder.RegisterType<ApplicationDbContext>() .AsSelf() .InstancePerRequest();...

How to register a type with autofac after container creation

c#,inversion-of-control,registration,autofac
I have an infrastructure singleton that I would like resolved out of autofac At container creation I register AppPaths as a singleton However, for a variety of reasons (testing, a few infrastructure things) I would like to be able to swap that instance out with a new one during runtime....

How can I create a specific object type at runtime?

c#,ninject,inversion-of-control,ioc-container
I have an interface that is implemented by all of my classes which are responsible for exporting data to different formats. Sample code: public interface IExport { string Exporter(); } public class ExcelExport : IExport { public string Exporter() { return "excel"; } } public class PdfExport : IExport {...

Autofac - How to get class name while creating instance

c#,dependency-injection,inversion-of-control,autofac,ioc-container
I have question about Autofac : How can I get name of class which request instance from container? Is it possible to get name of the class "Autofac_Test" passed into constructor by autofac when object is created? My code: using System; using System.Diagnostics; using System.Reflection; using Autofac; using Xunit; public...

Spring - autowired fields are null

java,spring,dependency-injection,inversion-of-control,autowired
I faced a problem with Spring Framework: @Autowired are null, but Spring doesn't throw any exceptions, and I can't understand, why are these fields null. I have a class: package com.processing.gates; public class Main { private final ApplicationContext context = Context.getContext(); @Autowired private PaymentGateFactory paymentGateFactory; @Autowired private CalculatorChooser calculatorChooser; //......

What is the properusage of InstancePerOwned in autofac dependency injection

dependency-injection,inversion-of-control,autofac
I wanted to know what is the proper usage of InstancePerOwned() in Autofac. How can I use that when resolving dependencies?

Is possible constructor injection using deserialization?

c#,serialization,ninject,inversion-of-control,ioc-container
On the following code: var serializer = new XmlSerializer(typeof(MyPOCOType)); using (var reader = XmlReader.Create(fileName)) { var pocoInstance = (MyPOCOType)serializer.Deserialize(reader); } I am using ninject. The MyPOCOType has an dependency that is passed by constructor injection. The instance of MyPOCOType is being created by the Deserialize method, so the dependencies are...

Inject object as lazy loading

c#,.net,model-view-controller,ninject,inversion-of-control
I have MVC code like below. I use nInject for IoC. I wonder when I push request to do for example SendMail there is create controller object, nInject create subobjects for both readonly objects: _mailSrv and _dbSrv, but I need in this request only one variable. Is it possible to...

How can I correctly use StructureMap (or any other IoC container) on a multi layered solution?

dependency-injection,inversion-of-control,ioc-container,structuremap,structuremap3
I have a 3 layer solution with the following structure: UI -> BLL <- DAL The UI is an ASP.NET MVC application. Each controller requires BLL components on its constructor. And each BLL component requires DAL components on its constructor. In the past I used StructureMap as the IoC container....

What does decoupling two classes at the interface level mean?

java,spring,inversion-of-control,software-engineering
Lets say we have class A in package A and class B in package B . If object of class A has reference to class B, then the two classes are said to have coupling between them. To address the coupling, it is recommended to define an interface in package...

Castle.Windsor IoC-container specific configuration

c#,dependency-injection,inversion-of-control,castle-windsor,ioc-container
I have chosen Castle.Windsor as IoC container for my app. This is my first IoC expirience so I need an advice configuring it. The root class of the app is Scheduler. It plans and performs different kinds of "jobs". Each job implements IWorker interface, so I decided to inject a...

ReactJS.Net on MVC5 fails to resolve dependency

asp.net-mvc-5,inversion-of-control,reactjs,tinyioc,reactjs.net
I'm trying to set up an ASP.Net MV5 application to work with ReactJS.Net, including server side rendering and bundling. Unfortunately, it fails with this exception: An exception of type 'React.TinyIoC.TinyIoCResolutionException' occurred in React.dll but was not handled in user code Additional information: Unable to resolve type: React.ReactEnvironment This exception occurs...

SimpleInjector duplicate registrations for RegisterManyForOpenGeneric for implementations with more than one interface

c#,inversion-of-control,ioc-container,simple-injector
I have an issue regarding automatic registration of IEventHandler<> with RegisterManyForOpenGeneric which results in duplicate registrations (something I am doing wrong I am sure). In my application an event is raised by an external input which is then dispatched to all classes which implement the IEventHandler<> of the incoming event...

Binding Model to ViewModel (WPF)

wpf,mvvm,inversion-of-control,prism,ioc-container
I'm making the move from MVP to MVVM, and a little confused as to how best bind the ViewModel to the Model. I understand how we can leverage WPF's data binding infrastructure to route events between the View and ViewModel using ICommand and INotifyPropertyChanged interface, e.g., the View: public class...

Can mvc 5 application has IoC out of the box?

asp.net-mvc,inversion-of-control
How is it possible that fresh mvc 5 application just reated from template has dependencies injected into controller? public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } This what you can see in Account Controller in just created project....

Constructor Injection vs IocFactory

c#,.net,dependency-injection,inversion-of-control
Today at work a collegue and I had a discussion about the following: Basically we have a rule engine which works in the following way: RuleExecutor Gets all rules to execute in the constructor like public RuleExecutor(ICollection<IRule> rulesToExecute) { ... } Executes all rules by calling rule.ApplyRule(); for each rulesToExecute...

IoC and Deserialization trouble

c#,serialization,inversion-of-control,ninject
I am using Ninject for IoC. UPDATE My repository uses XML Serializer to persist objects. How do I inject dependencies after deserializing an entity with behavior and state in the same class (POCO) and without using the service locator anti-pattern? This is the Save method: public void Save(IIntegrationService service) {...

Implementing Domain Event Handler pattern in C# with Simple Injector

c#,generics,inversion-of-control,simple-injector
I am trying to implement the Domain Event pattern in C# using Simple Injector. I have simplified my code to be in one file that can be ran as a console app and have excluded the Simple Injector code to keep things clear for the purpose of this question. The...

Autofac constructor chaining

c#,inversion-of-control,decorator,autofac
How would I implement the equivalent using Autofac to output 123. I've had a look at the following but I don't think it quite fits in with what I'm trying to achieve. http://docs.autofac.org/en/latest/advanced/adapters-decorators.html Maybe someone can enlighten me - is this decorator? using System; namespace Prototypes.Decorator { public class Program...

Injecting bean dependencies with Spring Java based configuration

java,spring,dependency-injection,inversion-of-control,spring-java-config
I'm trying to understand Spring Java based configuration. Typically I might have an XML configuration containing something like: <context:property-placeholder location="jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:ur="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource" />...

MvvmLight's SimpleIoc breaking in Xamarin Forms 1.3 Android and iOS app, but not in Windows Phone

xamarin,inversion-of-control,mvvm-light,xamarin.forms,common-service-locator
I am working on a Xamarin Forms app and all is going well with the Windows Phone building and running. However when I try and run the Android version, it build OK and then fails and I get an exception when calling the ServiceLocator to resolve ViewModel in the ViewModelLocator....

Castle Windsor DI installer: dependency factory method has nested dependency on ApiController property

asp.net-web-api,dependency-injection,inversion-of-control,castle-windsor,ioc-container
I am trying to implement DI with Castle Windsor. Currently I have a controller with overloaded constructors like this (this is an antipattern as described here: https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=97): public class MyController : ApiController { protected IStorageService StorageService; protected MyController() { StorageService = StorageServiceFactory.CreateStorageService(User.Identity as ClaimsIdentity); } protected MyController(IStorageService storageService) { StorageService...