Dynamic dependency injection |
We had similar requirement once, so what we did was use a factory pattern
and add all the implementations in factory class implementation using
spring.
That ways, when on run time we would know which implementation to use, we
would make a call to my factory to provide implementation class.
Also, anytime you have more implementations you could update spring
configuration for factory class.
This may not be close to design you have in mind, but this solved the
purpose for us.
Cheers !!
|
property injection using autofac 3.1.1 |
The problem you have is Main method is static. Instanciate a class of
Program and use is as non static class
class Program
{
public ISodaService s { get; set; }
static void Main(string[] args)
{
var resolver=SetUpContainer();
var instance=resolver.Resolve<Program>();
instance.Execute(args);
}
public void Execute(string[] args)
{
Console.Write(s.GetSoda());
Console.Read();
}
private Autofac.IContainer void SetUpContainer()
{
var builder = new ContainerBuilder();
builder.RegisterType<Soda>().As<ISoda>();
builder.RegisterType<SodaService>().As<ISodaService>().PropertiesAutowired();
bui
|
Autofac Property Injection after a type is Registered |
Use the WithProperty or WithProperties methods if you want to set the
injections at registration rather than at initialization.
ie builder.RegisterType(customType).WithProperty("PropertyName", "value");
|
Autofac attribute injection failing on attributes |
Your property of type IDataAccessProvider has to be public for injection to
work. You can still mark DebugLogAttribute, IDataAccessProvider and it's
implementation as internal if you prefer.
[DebugLogAttribute]
public class HOmeController : Controller
{
public ActionResult Index()
{
return View();
}
}
internal class DebugLogAttribute : ActionFilterAttribute
{
public IDataAccessProvider DataAccess { get; set; }
public override void OnActionExecuting(ActionExecutingContext
filterContext)
{
Debugger.Break();
}
public override void OnActionExecuted(ActionExecutedContext
filterContext)
{
Debugger.Break();
}
}
internal interface IDataAccessProvider {}
internal class DataAccessProvider:IDataAccessProvider {}
|
How do I create a Quartz.NET’s job requiring injection with autofac |
The problem is that your AutofacJobFactory is not creating the ReleaseJob
(you are doing this with JobBuilder.Create<ReleaseJob>() instead), so
the IoC container is not aware of it's instantiation meaning dependency
injection cannot occur.
The following code should work:
sched = schedFact.GetScheduler();
sched.JobFactory = new AutofacJobFactory(container);
sched.Start();
// construct job info
JobDetailImpl jobDetail = new JobDetailImpl("1Job", null, typeof(ReleaseJob
));
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("1JobTrigger")
.WithSimpleSchedule(x => x
.RepeatForever()
.WithIntervalInSeconds(5)
)
.StartNow()
.Build();
sched.ScheduleJob(jobDetail, trigger);
Note that in this example we are not using JobBuilder.Create<Rel
|
Autofac Register Different Implementation To Different Controllers |
Have you assigned the names "TestService1" and "TestService2"? e.g.
builder.RegisterType<TestService1>().As<ITestService1>().Named("TestService1");
builder.RegisterType<TestService2>().As<ITestService2>().Named("TestService2");
|
Circular Dependency in Dependency Injection via Constructors |
Disclaimer: I don't know much about Netty, these are just some thoughts
from reading your code:
I don't see any problem with MyServerInitializer. MyServerInitializer does
not have any dependenciesy on MyServerHandler or MyServer. That's fine. It
would be worse if the constructor of MyServerInitializer would require
MyServerHandler instead of ChannelInboundHandlerAdapter.
If possible you should change the constructor parameter of MyServer from
MyServerInitializer to ChannelInitializer<SocketChannel>.
The problem is that MyServerHandler depends on MyServer while MyServer has
a indirect runtime dependency on MyServerHandler. I would try to get rid of
the MyServer dependency in MyServerHandler. To do this you can:
Move the updateInteger() method from MyServer into another class, le
|
Autofac dependency resolution error |
Solution 1.
You are registered a IDbContext as Named service.
.Named<IDbContext>("Speed")
Thus, you must use a ResolveNamed method.
_container.ResolveNamed<IDbContext>("Speed");
Solution 2.
You can just register a IDbContext as a type. In this case, the method
Resolve() should work correctly.
builder.Register<IDbContext>(c =>
new
DbContext(ConfigurationManager.ConnectionStrings["Speed"].ConnectionString))
.InstancePerDependency();
|
Dependency Injection - When to use property injection |
Dependency Injection is not a goal, but a solution to a particular set of
problems. For instance, Dependency Injection makes it easy to replace
abstractions for unit testing and makes your application more flexible,
since you can swap, decorate and intercept dependencies without the
consuming class knowing.
That doesn't mean that you should inject every dependency a class has,
since it must help you in making the class more testable and the system
more maintainable. So you have to ask yourself whether it helps from a
testing perspective to inject those dictionaries from the outside or if it
helps to make your application more flexible.
This last question is hard to answer for me, since your question doesn't
have enough detail. But here are some pointers:
The only things you typically wa
|
how to create autofac factory for dependency resolution |
public class DbContextFactory
{
private ILifetimeScope m_RootLifetimeScope;
public DbContextFactory(ILifetimeScope rootLifetimeScope)
{
m_RootLifetimeScope = rootLifetimeScope;
}
public IDbContext CreateDbContext()
{
if (logic for selection first dbcontext)
{
return
m_RootLifetimeScope.ResolveNamed<IDbContext>("first");
}
else if (logic for selection second dbcontext)
{
return
m_RootLifetimeScope.ResolveNamed<IDbContext>("second");
}
else
{
throw new NotSupportedException();
}
}
}
//registration
builder.RegisterType<DbContextFactory>().SingleInstance();
//using
var factory = yourContainer.Resolve<DbContextFactory>();
|
Autofac, MVC (with ActionFilters), Web.Forms - dependency resolution conflict |
Actually there are two bugs? in Autofac which causing this behavior:
Bug #1: As side effect of the fix of Issue 351 the
AutofacDependencyResolver needs to registered in the created Request bound
LifeTimeScopes. The MVC intergration does this but the Winforms integration
of course does not.
Bug? #2: Both the RequestLifetimeScopeProvider and the ContainerProvider
stores the created ILifetimeScope with the same key
HttpContext.Current.Items:
static ILifetimeScope LifetimeScope
{
get { return
(ILifetimeScope)HttpContext.Current.Items[typeof(ILifetimeScope)]; }
set { HttpContext.Current.Items[typeof(ILifetimeScope)] = value; }
}
So there is a little bit race condition here because depending on which
module gets executed first the WebForms or the MVC intergartion
ILifetimeScope wins
|
Resolving or injecting dependency in global.asax using autofac |
This allowed me to resolve my dependencies finally.
using(var scope = container.BeginLifetimeScope("AutofacWebRequest"))
{
scope.Resolve<SecurityConfig>().RegisterActivities();
}
|
Autofac dependency resolver passes the same value for parameters when resolving the service |
Figured it out!
I had to replace this:
var factory = _dependencyResolver.GetService<Func<string, string,
string, IContext>>();
IContext context = factory(contextToken, hostUrl, request.Url.Authority);
with this:
var context =
_dependencyResolver.RequestLifetimeScope.Resolve<IContext>(
new NamedParameter("contextToken", contextToken),
new NamedParameter("hostUrl", hostUrl),
new NamedParameter("appUrl", request.Url.Authority));
|
ASP.NET MVC dependency injection? |
Unity is creating new instances of the dependencies, which means that as
both IUnitOfWorkManager and ILocalizationService are instantiated, their
dependencies are instantiated separately. Find a way to share the
dependency on the context; ideally only the unit of work should be really
aware of it, and anything else should go through the unit of work to make
changes to the context, I think.
|
Dependency Injection with XML in PHP |
My first question is, does anyone foresee any problems with a schema
similar to the above?
You are re-inventing the wheel. PHP is a scripting language, so instead of
an XML file you can as well just use a PHP file - it's much more expressive
for - well - PHP :)
My second question is, how should I go about translating this into an my
definitions array? This question isn't about how to parse the XML, rather
the design of the array that will hold the information once parsed.
You can do that by mocking with an array first and then thinking backwards,
like how to store the information you have in the array into an XML file -
or just drop the XML completely and just load the array (see the point
above).
My last question is, what about adding a definition for persistence? For
examp
|
Is Dependency Injection a must in asp.net MVC? |
Dependency Injection is not a requirement for using ASP.net MVC. You can
definitely build an MVC app without it.
Where it will come in handy is if you want to perform unit testing on your
application. If you would like to unit test an action in a controller, if
you have DI set up, then you can mock your dependencies that are included
in the controller constructor (that DI takes care of when the app is
running) and set up responses to return when they are called by the Action.
This is much harder and impractical (if not impossible) to do if you are
not using Dependency Injection. In such a case, if you want to use Unit
Testing, it will be very hard to write pure unit tests of your Actions,
since you will have no easy way to mock your service and data access layers
for your tests.
And as
|
Too much dependency injection? |
I wouldn't worry about going overboard with dependency injection. You have
already stated yourself some of the benefits that you have seen from
adopting it (test-ability, encouraging good design re separation of
concerns).
A criticism I have heard made of dependency injection (and IoC) is that it
can introduce too much complexity. While it is certainly possible to
over-complicate things due to a bad implementation, I can not agree with
this complaint as an intrinsic problem with dependency injection.
The thing to keep an eye on is that you choose the right level of
abstraction and indirection for your dependencies that will give you the
flexibility you need. Too many levels of indirection can add complexity for
no value, but I would argue that this is an orthogonal issue to dependency
in
|
Dependency Injection issue |
You want to store and use the injected component as opposed to a global
one.
class Posts{
protected $dbconnection;
public function __construct($dbconn){
// save the injected dependency as a property
$this->dbconnection = $dbconn;
}
public function getMemberPosts($id, $members){
// also inject the members into the function call
// do something cool with members to build a query
// use object notation to use the dbconnection object
$this->dbconnection->query($query);
}
}
|
php dependency injection with a container |
From my understanding in Silex/Symfony2, is that there is no 'magical way'
to do these type of things.
For my first question: It is allowed to add objects that are created before
the container.
In Symfony2, in Kernel:initializeContainer function, Kernel adds itself to
the container ($this->container->set('kernel', $this);) and later on,
in the xml files, services are injected with Kernel (<argument
id="kernel" type="service" />).
In Silex, Application:__construct function creates and adds objects to the
container. Application injects itself to the ServiceProviders, so these
providers can inject dependencies to their objects and add them to the
container.
$container->manualAdd('_logger', $logger); is correct.
For my second question: depends on how I want to handle it.
|
Why use a Dependency Injection container? |
You make a good point. Your second example is using what Mark Seemann might
refer to as 'Poor Man's DI'. It's still DI but you're doing it yourself.
IoC containers come into their own when you begin to manage the injection
of many different types and features like lifestyle management and
registration of types by convention become massive labour savers.
For smaller tasks with minimal dependency management, as you've suggested,
they are probably overkill.
I would highly recommend Seemann's book and blog if you want to find out
more. IMHO, he explains the topic better than anyone.
|
EF: Entity Dependency injection |
For those using a DI container, you might try to inject the
dependencies into the aggregate root. That leads to a whole host of
problems, which are so numerous I won’t derail a perfectly good post
by getting into it. Instead, there’s another, more
intention-revealing option: the double dispatch pattern.
Quoted from a post by Jimmy Bogard. Find that post (which includes an
example) here:
http://lostechies.com/jimmybogard/2010/03/30/strengthening-your-domain-the-double-dispatch-pattern/.
|
Ember.js dependency injection |
Generally you don't want to be wiring up all of the pieces yourself, you
want to use needs in your controller to let Ember do it for you. I'm not
sure at all how Ember deals with 3 level class names vs two, so I'm just
going to demonstrate with two levels. (MyApp.ApiContact instead of
MyApp.Api.Contact.) Also, send is a native Ember method that is present on
all (or almost all) objects, so you'd want to use something like
sendMessage instead so that you don't end up with hard to diagnose
conflicts. After you have told Ember that your controller needs
apiContact, you can just call this.get('controllers.apiContact') to get a
hold of it.
MyApp.LayoutFooterController = Ember.ObjectController.extend({
needs : ['apiContact'],
// All your other stuff here
sendMessage : function(){
|
Dependency Injection and dependencies not used |
Update: after re-reading carefully your question, here is another advice:
yes, every class has different dependencies.
Don't inject every object into every other object. For example, some
services might need DAOs, so inject them. But if a service doesn't need a
DAO, don't inject any DAO.
The rest of my answer is valid if you have (for example) a service that
needs a DAO (and thus a DB connection) not for every method.
What you may be looking for is lazy injection.
It is the act of injecting a dependency not loaded, so that the object is
loaded only if/when used.
In conrete terms, that means injecting a proxy object, that would look like
and behave exactly like the original object (for example, the db
connection).
Several DI container (frameworks) support this so you don't have to c
|
How do you use HK2 dependency injection with Jersey 2.0? |
Turns out I just needed to add a couple of lines of code, but I'll post it
here in case anyone else has the same problem.
ResourceConfig rc = new ResourceConfig();
rc.packages("com.danny.resources");
rc.registerInstances(new StatusModule(useFake), new
NetworkModule(useFake));
GrizzlyHttpContainer resourceConfigContainer = ContainerFactory
.createContainer(GrizzlyHttpContainer.class, rc);
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri);
server.getServerConfiguration().addHttpHandler(resourceConfigContainer,
"/");
The ResourceConfig lets you tell the server where to find your dynamic
resources, in my case "com.danny.resources". It also allows you to register
hk2 binders which will be used to inject those resources into your code.
Hope this helps someone along t
|
Dependency Injection where to use "new" Operator |
Some DI frameworks provide factories for this purpose, so you won't ever
need to call the new operator. For example, Castle Windsor provides Typed
factories.
With this, you'd just define the interface:
public interface IUserFactory
{
public IUser CreateUser(string username, string password...);
}
And register that interface as a factory. Windsor will provide the
implementation for this interface, which will match the following
constructor on the following class (assuming you registered User as a
component):
public class User : IUser
{
public User(string username, string password ...)
{
}
}
Logically, your controller would also have to declare this factory as a
dependency.
public class AccountController
{
private IUserFactory _userFactory;
public AccountController(IUs
|
Little bit confused with Dependency Injection |
I think you misunderstood Avoiding Your Code Becoming Dependent on the
Container. It discourage you from doing something like this:
class Foo
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function foo()
{
$bar = $this->container->get('bar');
$bar->bar();
}
}
In this way, your code is tied to a service container where service bar is
present.
So, in general, only ask for what you need (which is bar), and don't ask
for the whole universe (which is service_container).
By the way, without using $container->get(), you can still use something
like $bar = new Bar(); $foo = new Foo($bar);
|
dependency injection in a servlet 3.0 web app? |
EJB 3 dependency injection is extremely simple to use. A single annotation,
@EJB, causes the injection of a declared bean. The injection of the SomeDAO
bean into a Servlet 3.0 looks like this:
@WebServlet(name="Messenger", urlPatterns={"/Messenger"})
public class Messenger extends HttpServlet {
@EJB
SomeDAO someDAO;
}
The injected SomeDAO bean could be an interface or a no-interface view
bean. As long as there is only one implementation of the interface, it will
be injected without any ceremony.
|
Logging and Dependency Injection |
I need some way of logging in nearly each class in my application.
Think again. If you think you need logging in nearly every class, there is
something wrong with your design. This Stackoverflow answer talks about
what might be wrong with your design. It's answered in the context of .NET,
but the answer is applicable to Java as well.
That answer mainly talks about exception logging, for non-exception logging
I would say: Prevent logging too much information at too many places. For
each info or warning that you want to log, question whether this shouldn't
have been an exception in the first place. For instance, don't log things
like "we shouldn't be in this branch", but throw an exception!
And even when you want to log debug information, does anyone ever going to
read this? You'll en
|
How does dependency Injection know what variables to pass? |
My best bet is that IoC containers in PHP use Reflection (just as IoC
containers in .NET and Java do). Here is an example that shows how to
reflect over a type and get the parameter names of the parameters of its
constructor:
$reflector = new ReflectionClass('SomeClass');
$parameters = $reflector->getConstructor()->getParameters();
foreach ($parameters as $parameter) {
echo $parameter->name;
}
|
Dependency Injection in ASP.NET Web API using Unity error |
Found the answer, seems like the blog is outdated as I dont even have to
create the IoCContainer as I just need to install Unity.WebAPI and just set
the DependencyResolver to new
Unity.WebApi.UnityDependencyResolver(container);
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new
UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new
Unity.WebApi.UnityDependencyResolver(container);
return container;
}
credit:
http://netmvc.blogspot.com/2012/04/dependency-injection-in-aspnet-mvc-4.html
|
Dependency Injection vs Layered Architecture |
This is really a fairly complex topic, and there are many ways of doing an
n-tier architecture. No one way is "the right way", and how you do it
depends on your needs as much as it does your personal preferences.
Dependency Injection is about managing dependencies. If your object should
be unaware of any dependency, then you would not write your objet in the
way you mentioned. You would instead have some other service or method
that would populate the data in an agnostic way. Data doesn't mean
"Database" either. So IDataAccess could mean it comes from a database, or
it comes from a network socket or it comes from a file on disk. The whole
point here is that Address does not choose what dependencies it creates.
This is done through configuration at the composition root.
Things need
|
Spring 3.1 dependency injection failed |
You need to use the Struts 2 Spring plugin, otherwise Spring has no idea it
should be doing anything with the S2 actions. Once you drop the S2 plugin
in (using Maven so the other dependencies come automagically) you're
basically done after configuring the Spring context loader listener.
You do not need to define your actions in the Spring config file, but you
may. Whether or not you need to depends on how you're doing your wiring,
e.g., if you're auto-wiring by name, you can skip it.
|
Too much dependency injection for web app and web service layer? |
Your question is highly subjective, but I will try to answer it anyway.
You are breaking your application into logical tiers that can each be unit
tested. This is generally a good thing. Different abstraction points or
interfaces mean that you can easily swap the logic if you need to down the
road, which makes the application more extensible and maintainable.
Is it too much?
That really depends on several factors - deadlines, budget, the life
expectancy of the project, etc. The more layers you need to build, the
bigger the upfront investment and the more layers you need to maintain
later. But the abstractions make it easier to swap business logic - which
often makes it worth the upfront cost.
But is it too much for your DI container to handle? No. Keep in mind the
purpose of DI is to s
|
How to mock not implemented Dependency injection? |
What about this?
public databaseactivity(IDbManager dbManager = null)
{
DbManager dbManager = dbManager ?? new DbManager();
// ...
}
If you need to re-create instances (like it seems to be the case with the
ServiceclientFactory), you need to inject a factory (I would try to avoid
this, because it makes things more complicated):
public databaseactivity(ServiceclientFactory serviceClientFactory = null,
/*...*/)
{
// ...
this.serviceClientFactory = serviceClientFactory ?? new
DefaultServiceClientFactory();
}
public int insert(bo obj)
{
serviceClient = this.serviceClientFactory.CreateServiceClient();
serviceClient.insert(obj);
}
|
Dependency Injection, need factory like functionality |
@Component
public class AnimalFactory {
@Autowired
private Dog dog;
@Autowired
private Cat cat;
public Animal create(String kind) {
if (king.equals("dog") {
return dog;
}
else {
return cat;
}
}
}
@Component
public class Cat extends Animal {
...
}
@Component
public class Dog extends Animal {
...
}
@Component
private class Client {
@Autowired
private AnimalFactory factory;
public void foo() {
Animal animal = factory.create("dog");
animal.run();
}
}
|
Can you use Angular dependency injection instead of RequireJS? |
You must have a
<script src="file.js"></script>
per each file that you're using. It should work once you have all the
references in place.
Or ... check out this article for a way to roll-your-own runtime resolution
of controllers.
|
does dependency injection promotes facades? |
You can change the public class to the interface and all other parts of the
program will only know about the interface. Here's some sample code to
illustrate this:
public interface IFacade
{
void DoSomething();
}
internal class FacadeImpl : IFacade
{
public FacadeImpl(Alfa alfa, Bravo bravo)
{
}
public void DoSomething()
{
}
}
internal class Alfa
{
}
internal class Bravo
{
}
|
use dependency injection in eclipse plugin |
I assume you are mainly interested in the dependency mechanisms of the
Eclipse 4 workbench. I recommend these tutorials and articles for an
introduction:
an Eclipse wiki page describing how this was introduced in Eclipse
a great tutorial introducing the basics of this
mechanism and how to use it in your plugin
and of course a huge tutorial on vogella about all things E4 development,
where dependency injection starts at chapter 23.
|
Constructor Dependency Injection in Spring MVC 3 |
For constructor injection you need to declare your bean as a spring bean in
your spring-context or with an annotation.
However I doubt that it will pass a parameter as a constructor when used as
a formbean. Spring should set the parameters with the setters. Use a
standard constructor and add a setter.
|
Multi-project dependency injection |
This will have to be a bit vague since you don't say anything about what
you're using to do your dependency injection, but FWIW, we have a current
multi-project mixed scala/java environment injected with guice, so maybe
this will be helpful to you.
Since guice allows you to include modules (i.e. nest one module inside
another) this allows for hierarchical module structure (they must assume
people will use it like this - there's even a grapher included with the
distribution to make a nice picture of the relationship between your
modules). So, for example, you might have a module that includes database
connections and various objects that interact directly with that, and you'd
then include that module directly with anything that interacts with the db
layer.
|