Search Results

Search found 1303 results on 53 pages for 'injection'.

Page 5/53 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Dependency Injection -Colloquial explanation

    - by nettguy
    Recently I was asked to express the DI in colloquial explanation. I answered : 1) I am going to a hotel.I ordered food.The hotel management asks me to clean the plates and clean the tables.So here i am a client,I am responsible for managing the service (Instantiating,executing,disposing).But DI decouples such tasks so the service consumer no need not worry about controlling the life cycle of the service. 2) He also asked is there any microsoft API follows DI ?.I answered (This was my guess) In WCF you can create a Proxy using ChannelFactory that controls the life time of your factory. for item (1) he said only 10% is correct for item(2) he said that is factory pattern not dependency injection. Actually what went wrong in my explanation (apart from my bad English) ? What is the real answers for those? I am waiting for your valuable suggestions.

    Read the article

  • internet explorer, google chrome injection

    - by Volim Te
    I wrote code that injects a function in Internet Explorer/Chrome but it doesn't work with these processes. Basically, it fills one big structure with all the APIs my function needs, strings, and other data, then it opens a process to get a handle, virtualallocex to allocate enough memory to store a function and structure there, and it writes the function and the structure in allocated memory. It then runs createremotethread there with the function as a starting address and structure as parameter. It works all great with calc/notepad/winamp processes but I have problems with browser injection. I'm wondering what could it be, I'm using these APIs. x.xCreateFile x.xWriteFile x.xCloseHandle x.xSleep x.xVirtualAlloc x.xVirtualFree x.xMessageBox x.xLoadLibrary x.xShellExecute Is it because browsers are protected now and they're running with lowest privileges?

    Read the article

  • WCF and Unity - Dependecy Injection

    - by Michael
    I'm trying to hock up WCF with dependecy injection. All the examples that I have found is based on the assumptions that you either uses a .svc (ServiceHostFactory) service or uses app.config to configure the container. Other examples is also based on that the container is passed around to the classes. I would like a solution where the container is not passed around (not tightly coupled to Unity). Where I don't uses a config file to configure the container and where I use self-hosted services. The problem is - as I see it - that the ServiceHost is taking the type of the service implementation as a parameter so what different does it do to use the InstanceProvider? The solution I have come up with at the moment is to register the ServiceHost (or a specialization) an register a Type with a name ( e.g. container.RegisterInstance<Type>("ServiceName", typeof(Service);). And then container.RegisterType<UnityServiceHost>(new InjectionConstructor(new ResolvedParameter<Type>("ServiceName"))); to register the ServiceHost. Any better solutions out there? I'm I perhaps way of in my assumptions. Best regards, Michael

    Read the article

  • Factories, or Dependency Injection for object instantiation in WCF, when coding against an interface

    - by Saajid Ismail
    Hi I am writing a client/server application, where the client is a Windows Forms app, and the server is a WCF service hosted in a Windows Service. Note that I control both sides of the application. I am trying to implement the practice of coding against an interface: i.e. I have a Shared assembly which is referenced by the client application. This project contains my WCF ServiceContracts and interfaces which will be exposed to clients. I am trying to only expose interfaces to the clients, so that they are only dependant on a contract, not any specific implementation. One of the reasons for doing this is so that I can have my service implementation, and domain change at any time without having to recompile and redeploy the clients. The interfaces/contracts will in this case not change. I only need to recompile and redeploy my WCF service. The design issue I am facing now, is: on the client, how do I create new instances of objects, e.g. ICustomer, if the client doesn't know about the Customer concrete implementation? I need to create a new customer to be saved to the DB. Do I use dependency injection, or a Factory class to instantiate new objects, or should I just allow the client to create new instances of concrete implementations? I am not doing TDD, and I will typically only have one implementation of ICustomer or any other exposed interface.

    Read the article

  • Correctly use dependency injection

    - by Rune
    Me and two other colleagues are trying to understand how to best design a program. For example, I have an interface ISoda and multiple classes that implement that interface like Coke, Pepsi, DrPepper, etc.... My colleague is saying that it's best to put these items into a database like a key/value pair. For example: Key | Name -------------------------------------- Coke | my.namespace.Coke, MyAssembly Pepsi | my.namespace.Pepsi, MyAssembly DrPepper | my.namespace.DrPepper, MyAssembly ... then have XML configuration files that map the input to the correct key, query the database for the key, then create the object. I don't have any specific reasons, but I just feel that this is a bad design, but I don't know what to say or how to correctly argue against it. My second colleague is suggesting that we micro-manage each of these classes. So basically the input would go through a switch statement, something similiar to this: ISoda soda; switch (input) { case "Coke": soda = new Coke(); break; case "Pepsi": soda = new Pepsi(); break; case "DrPepper": soda = new DrPepper(); break; } This seems a little better to me, but I still think there is a better way to do it. I've been reading up on IoC containers the last few days and it seems like a good solution. However, I'm still very new to dependency injection and IoC containers, so I don't know how to correctly argue for it. Or maybe I'm the wrong one and there's a better way to do it? If so, can someone suggest a better method? What kind of arguments can I bring to the table to convince my colleagues to try another method? What are the pros/cons? Why should we do it one way? Unfortunately, my colleagues are very resistant to change so I'm trying to figure out how I can convince them.

    Read the article

  • dll injection using C

    - by AJINKYA
    hey i m trying to inject a dll into a process i.e lsass.exe to get hashes.Its a bit hacky but cant help its my project. I have a code of dll injection but in visual C++ it gives errors such as.. at TEXT("LoadLibraryA"))))----argument const wchar incompatible with LPCSTR at lpFuncAddr-----------argument type "LPVOID" incompatible with parameter type "LPTHREAD_START ROUTINE" CODE: BOOL InjectDLL(DWORD dwProcessId, LPCSTR lpszDLLPath) { HANDLE hProcess, hThread; LPVOID lpBaseAddr, lpFuncAddr; DWORD dwMemSize, dwExitCode; BOOL bSuccess = FALSE; HMODULE hUserDLL; //convert char to wchar char *lpszDLLPath = "hash.dll"; size_t origsize = strlen(orig) + 1; const size_t newsize = 100; size_t convertedChars = 0; wchar_t dllpath[newsize]; mbstowcs_s(&convertedChars, dllpath, origsize, orig, _TRUNCATE); if((hProcess = OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION |PROCESS_VM_WRITE|PROCESS_VM_READ, FALSE, dwProcessId))) { dwMemSize = wcslen(dllpath) + 1; if((lpBaseAddr = VirtualAllocEx(hProcess, NULL, dwMemSize, MEM_COMMIT, PAGE_READWRITE))) { if(WriteProcessMemory(hProcess, lpBaseAddr, lpszDLLPath, dwMemSize, NULL)) { if((hUserDLL = LoadLibrary(TEXT("kernel32.dll")))) { if((lpFuncAddr = GetProcAddress(hUserDLL, TEXT("LoadLibraryA")))) { if((hThread = CreateRemoteThread(hProcess, NULL, 0, lpFuncAddr, lpBaseAddr, 0, NULL))) { WaitForSingleObject(hThread, INFINITE); if(GetExitCodeThread(hThread, &dwExitCode)) { bSuccess = (dwExitCode != 0) ? TRUE : FALSE; } CloseHandle(hThread); } } FreeLibrary(hUserDLL); } } VirtualFreeEx(hProcess, lpBaseAddr, 0, MEM_RELEASE); } CloseHandle(hProcess); } return bSuccess; } int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { if(InjectDLL(PROCESSID, "hash.dll")) { MessageBox(NULL, TEXT("DLL Injected!"), TEXT("DLL Injector"), MB_OK); }else { MessageBox(NULL, TEXT("Couldn't inject DLL"), TEXT("DLL Injector"), MB_OK | MB_ICONERROR); } return 0; } i m a beginner to dll and windows programming so will appreciate your help.

    Read the article

  • Dependency Injection for objects that require parameters

    - by Andrew
    All of our reports are created from object graphs that are translated from our domain objects. To enable this, we have a Translator class for each report, and have been using Dependency Injection for passing in dependencies. This worked great, and would yield nice classes structured like this: public class CheckTranslator : ICheckTranslator { public CheckTranslator (IEmployeeService empSvc , IPaycheckService paySvc) { _empSvc = empSvc; _paySvc = paySvc; } public Check CreateCheck() { //do the translation... } } However, in some cases the mapping has many different grouping options. As a result, the c-tor would turn into a mix of class dependencies and parameters. public class CheckTranslator : ICheckTranslator { public CheckTranslator (IEmployeeService empSvc , IPaycheckService paySvc , bool doTranslateStubData , bool doAttachLogo) { _empSvc = empSvc; _paySvc = paySvc; _doTranslateStubData = doTranslateStubData; _doAttachLogo = doAttachLogo; } public Check CreateCheck() { //do the translation... } } Now, we can still test it, but it no longer really works with an IoC container, at least in a clean fashion. Plus, we can no longer call the CreateCheck twice if the settings are different for each check. While I recognize it's a problem, I don't necessarily see the right solution. It seems kind of strange to create a Factory for each class ... or is this the best way?

    Read the article

  • Dependency injection and factory

    - by legenden
    Trying to figure out how to best handle the following scenario: Assume a RequestContext class which has a dependency to an external service, such as: public class RequestContext : IRequestContext { private readonly ServiceFactory<IWeatherService> _weatherService; public RequestContext(ServiceFactory<IWeatherService> weatherService, UserLocation location, string query) { _weatherService = weatherService; ... What sort of dependency should I require in the class that will ultimately instantiate RequestContext? It could be ServiceFactory<IWeatherService>, but that doesn't seem right, or I could create an IRequestContextFactory for it along the lines of: public class RequestContextFactory : IRequestContextFactory { private readonly ServiceFactory<IWeatherService> _weatherService; public RequestContextFactory(ServiceFactory<IWeatherService> weatherService) { _weatherService = weatherService; } public RequestContext Create(UserLocation location, string query) { return new RequestContext(_weatherService, location, query); } } And then pass the IRequestContextFactory through constructor injection. This seems like a good way to do it, but the problem with this approach is that I think it hinders discoverability (devs must know about the factory and implement it, which is not really apparent). Is there a better/more discoverable way that I'm missing?

    Read the article

  • Considerations when architecting an application using Dependency Injection

    - by Dan Bryant
    I've begun experimenting with dependency injection (in particular, MEF) for one of my projects, which has a number of different extensibility points. I'm starting to get a feel for what I can do with MEF, but I'd like to hear from others who have more experience with the technology. A few specific cases: My main use case at the moment is exposing various singleton-like services that my extensions make use of. My Framework assembly exposes service interfaces and my Engine assembly contains concrete implementations. This works well, but I may not want to allow all of my extensions to have access to all of my services. Is there a good way within MEF to limit which particular imports I allow a newly instantiated extension to resolve? This particular application has extension objects that I repeatedly instantiate. I can import multiple types of Controllers and Machines, which are instantiated in different combinations for a Project. I couldn't find a good way to do this with MEF, so I'm doing my own type discovery and instantiation. Is there a good way to do this within MEF or other DI frameworks? I welcome input on any other things to watch out for or surprising capabilities you've discovered that have changed the way you architect.

    Read the article

  • spring - constructor injection and overriding parent definition of nested bean

    - by mdma
    I've read the Spring 3 reference on inheriting bean definitions, but I'm confused about what is possible and not possible. For example, a bean that takes a collaborator bean, configured with the value 12 <bean name="beanService12" class="SomeSevice"> <constructor-arg index="0"> <bean name="beanBaseNested" class="SomeCollaborator"> <constructor-arg index="0" value="12"/> </bean> </constructor-arg> </bean> I'd then like to be able to create similar beans, with slightly different configured collaborators. Can I do something like <bean name="beanService13" parent="beanService12"> <constructor-arg index="0"> <bean> <constructor-arg index="0" value="13"/> </bean> </constructor> </bean> I'm not sure this is possible and, if it were, it feels a bit clunky. Is there a nicer way to override small parts of a large nested bean definition? It seems the child bean has to know quite a lot about the parent, e.g. constructor index. I'd prefer not to change the structure - the parent beans use collaborators to perform their function, but I can add properties and use property injection if that helps. This is a repeated pattern, would creating a custom schema help? Thanks for any advice!

    Read the article

  • Dependecy Injection with Massive ORM: dynamic trouble

    - by Sergi Papaseit
    I've started working on an MVC 3 project that needs data from an enormous existing database. My first idea was to go ahead and use EF 4.1 and create a bunch of POCO's to represent the tables I need, but I'm starting to think the mapping will get overly complicated as I only need some of the columns in some of the tables. (thanks to Steven for the clarification in the comments. So I thought I'd give Massive ORM a try. I normally use a Unit of Work implementation so I can keep everything nicely decoupled and can use Dependency Injection. This is part of what I have for Massive: public interface ISession { DynamicModel CreateTable<T>() where T : DynamicModel, new(); dynamic Single<T>(string where, params object[] args) where T : DynamicModel, new(); dynamic Single<T>(object key, string columns = "*") where T : DynamicModel, new(); // Some more methods supported by Massive here } And here's my implementation of the above interface: public class MassiveSession : ISession { public DynamicModel CreateTable<T>() where T : DynamicModel, new() { return new T(); } public dynamic Single<T>(string where, params object[] args) where T: DynamicModel, new() { var table = CreateTable<T>(); return table.Single(where, args); } public dynamic Single<T>(object key, string columns = "*") where T: DynamicModel, new() { var table = CreateTable<T>(); return table.Single(key, columns); } } The problem comes with the First(), Last() and FindBy() methods. Massive is based around a dynamic object called DynamicModel and doesn't define any of the above method; it handles them through a TryInvokeMethod() implementation overriden from DynamicObject instead: public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { } I'm at a loss on how to "interface" those methods in my ISession. How could my ISession provide support for First(), Last() and FindBy()? Put it another way, how can I use all of Massive's capabilities and still be able to decouple my classes from data access?

    Read the article

  • Unity 1.2 Dependency injection of internal types

    - by qvin
    I have a facade in a library that exposes some complex functionality through a simple interface. My question is how do I do dependency injection for the internal types used in the facade. Let's say my C# library code looks like - public class XYZfacade:IFacade { [Dependency] internal IType1 type1 { get; set; } [Dependency] internal IType2 type2 { get; set; } public string SomeFunction() { return type1.someString(); } } internal class TypeA { .... } internal class TypeB { .... } And my website code is like - IUnityContainer container = new UnityContainer(); container.RegisterType<IType1, TypeA>(); container.RegisterType<IType2, TypeB>(); container.RegisterType<IFacade, XYZFacade>(); ... ... IFacade facade = container.Resolve<IFacade>(); Here facade.SomeFunction() throws an exception because facade.type1 and facade.type2 are null. Any help is appreciated.

    Read the article

  • Dependency Injection into your Singleton

    - by Langali
    I have a singleton that has a spring injected Dao (simplified below): public class MyService<T> implements Service<T> { private final Map<String, T> objects; private static MyService instance; MyDao myDao; public void set MyDao(MyDao myDao) { this. myDao = myDao; } private MyService() { this.objects = Collections.synchronizedMap(new HashMap<String, T>()); // start a background thread that runs for ever } public static synchronized MyService getInstance() { if(instance == null) { instance = new MyService(); } return instance; } public void doSomething() { myDao.persist(objects); } } My spring config will probably look like this: <bean id="service" class="MyService" factory-method="getInstance"/> But this will instantiate the MyService during startup. Is there a programmatic way to do a dependency injection of MyDao into MyService, but not have spring manage the MyService? Basically I want to be able to do this from my code: MyService.getInstance().doSomething(); while having spring inject the MyDao for me.

    Read the article

  • Dependency injection in constructors

    - by andre
    Hello everyone. I'm starting a new project and setting up the base to work on. A few questions have risen and I'll probably be asking quite a few in here, hopefully I'll find some answers. First step is to handle dependencies for objects. I've decided to go with the dependency injection design pattern, to which I'm somewhat new, to handle all of this for the application. When actually coding it I came across a problem. If a class has multiple dependencies and you want to pass on multiple dependencies via the constructor (so that they cannot be changed after you instantiate the object). How do you do it without passing an array of dependencies, using call_user_func_array(), eval() or Reflection? This is what i'm looking for: <?php class DI { public function getClass($classname) { if(!$this->pool[$classname]) { # Load dependencies $deps = $this->loadDependencies($classname); # Here is where the magic should happen $instance = new $classname($dep1, $dep2, $dep3); # Add to pool $this->pool[$classname] = $instance; return $instance; } else { return $this->pool[$classname]; } } } Again, I would like to avoid the most costly methods to call the class. Any other suggestions?

    Read the article

  • Stuck trying to get Log4Net to work with Dependency Injection

    - by Pure.Krome
    I've got a simple winform test app i'm using to try some Log4Net Dependency Injection stuff. I've made a simple interface in my Services project :- public interface ILogging { void Debug(string message); // snip the other's. } Then my concrete type will be using Log4Net... public class Log4NetLogging : ILogging { private static ILog Log4Net { get { return LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); } } public void Debug(string message) { if (Log4Net.IsDebugEnabled) { Log4Net.Debug(message); } } } So far so good. Nothing too hard there. Now, in a different project (and therefore namesapce), I try and use this ... public partial class Form1 : Form { public Form1() { FileInfo fileInfo = new FileInfo("Log4Net.config"); log4net.Config.XmlConfigurator.Configure(fileInfo); } private void Foo() { // This would be handled with DI, but i've not set it up // (on the constructor, in this code example). ILogging logging = new Log4NetLogging(); logging.Debug("Test message"); } } Ok .. also pretty simple. I've hardcoded the ILogging instance but that is usually dependency injected via the constructor. Anyways, when i check this line of code... return LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); the DeclaringType type value is of the Service namespace, not the type of the Form (ie. X.Y.Z.Form1) which actually called the method. Without passing the type INTO method as another argument, is there anyway using reflection to figure out the real method that called it?

    Read the article

  • Dependency injection in C++

    - by Yorgos Pagles
    This is also a question that I asked in a comment in one of Miško Hevery's google talks that was dealing with dependency injection but it got buried in the comments. I wonder how can the factory / builder step of wiring the dependencies together can work in C++. I.e. we have a class A that depends on B. The builder will allocate B in the heap, pass a pointer to B in A's constructor while also allocating in the heap and return a pointer to A. Who cleans up afterwards? Is it good to let the builder clean up after it's done? It seems to be the correct method since in the talk it says that the builder should setup objects that are expected to have the same lifetime or at least the dependencies have longer lifetime (I also have a question on that). What I mean in code: class builder { public: builder() : m_ClassA(NULL),m_ClassB(NULL) { } ~builder() { if (m_ClassB) { delete m_ClassB; } if (m_ClassA) { delete m_ClassA; } } ClassA *build() { m_ClassB = new class B; m_ClassA = new class A(m_ClassB); return m_ClassA; } }; Now if there is a dependency that is expected to last longer than the lifetime of the object we are injecting it into (say ClassC is that dependency) I understand that we should change the build method to something like: ClassA *builder::build(ClassC *classC) { m_ClassB = new class B; m_ClassA = new class A(m_ClassB, classC); return m_ClassA; } What is your preferred approach?

    Read the article

  • C++ and Dependency Injection in unit testing

    - by lhumongous
    Suppose I have a C++ class like so: class A { public: A() { } void SetNewB( const B& _b ) { m_B = _b; } private: B m_B; } In order to unit test something like this, I would have to break A's dependency on B. Since class A holds onto an actual object and not a pointer, I would have to refactor this code to take a pointer. Additionally, I would need to create a parent interface class for B so I can pass in my own fake of B when I test SetNewB. In this case, doesn't unit testing with dependency injection further complicate the existing code? If I make B a pointer, I'm now introducing heap allocation, and some piece of code is now responsible for cleaning it up (unless I use ref counted pointers). Additionally, if B is a rather trivial class with only a couple of member variables and functions, why introduce a whole new interface for it instead of just testing with an instance of B? I suppose you could make the argument that it would be easier to refactor A by using an interface. But are there some cases where two classes might need to be tightly coupled?

    Read the article

  • Proper structure for dependency injection (using Guice)

    - by David B.
    I would like some suggestions and feedback on the best way to structure dependency injection for a system with the structure described below. I'm using Guice and thus would prefer solutions centered around it's annotation-based declarations, not XML-heavy Spring-style configuration. Consider a set of similar objects, Ball, Box, and Tube, each dependent on a Logger, supplied via the constructor. (This might not be important, but all four classes happen to be singletons --- of the application, not Gang-of-Four, variety.) A ToyChest class is responsible for creating and managing the three shape objects. ToyChest itself is not dependent on Logger, aside from creating the shape objects which are. The ToyChest class is instantiated as an application singleton in a Main class. I'm confused about the best way to construct the shapes in ToyChest. I either (1) need access to a Guice Injector instance already attached to a Module binding Logger to an implementation or (2) need to create a new Injector attached to the right Module. (1) is accomplished by adding an @Inject Injector injectorfield to ToyChest, but this feels weird because ToyChest doesn't actually have any direct dependencies --- only those of the children it instantiates. For (2), I'm not sure how to pass in the appropriate Module. Am I on the right track? Is there a better way to structure this? The answers to this question mention passing in a Provider instead of using the Injector directly, but I'm not sure how that is supposed to work. EDIT: Perhaps a more simple question is: when using Guice, where is the proper place to construct the shapes objects? ToyChest will do some configuration with them, but I suppose they could be constructed elsewhere. ToyChest (as the container managing them), and not Main, just seems to me like the appropriate place to construct them.

    Read the article

  • Global State and Singletons Dependency injection

    - by Manu
    this is a problem i face lot of times when i am designing a new app i'll use a sample problem to explain this think i am writing simple game.so i want to hold a list of players. i have few options.. 1.use a static field in some class private static ArrayList<Player> players = new ArrayList<Integer>(); public Player getPlayer(int i){ return players.get(i); } but this a global state 2.or i can use a singleton class PlayerList{ private PlayerList instance; private PlayerList(){...} public PlayerList getInstance() { if(instance==null){ ... } return instance; } } but this is bad because it's a singleton 3.Dependency injection class Game { private PlayerList playerList; public Game(PlayerList list) { this.list = list; } public PlayerList getPlayerList() { return playerList; } } this seems good but it's not, if any object outside Game need to look at PlayerList (which is the usual case) i have to use one of the above methods to make the Game class available globally. so I just add another layer to the problem. didn't actually solve anything. what is the optimum solution ? (currently i use Singleton approach)

    Read the article

  • DCI: How to implement Context with Dependency Injection?

    - by ciscoheat
    Most examples of a DCI Context are implemented as a Command pattern. When using Dependency Injection though, it's useful to have the dependencies injected in the constructor and send the parameters into the executing method. Compare the Command pattern class: public class SomeContext { private readonly SomeRole _someRole; private readonly IRepository<User> _userRepository; // Everything goes into the constructor for a true encapsuled command. public SomeContext(SomeRole someRole, IRepository<User> userRepository) { _someRole = someRole; _userRepository = userRepository; } public void Execute() { _someRole.DoStuff(_userRepository); } } With the Dependency injected class: public class SomeContext { private readonly IRepository<User> _userRepository; // Only what can be injected using the DI provider. public SomeContext(IRepository<User> userRepository) { _userRepository = userRepository; } // Parameters from the executing method public void Execute(SomeRole someRole) { someRole.DoStuff(_userRepository); } } The last one seems a bit nicer, but I've never seen it implemented like this so I'm curious if there are any things to consider.

    Read the article

  • Dependency Injection: How to pass DB around?

    - by Stephane
    Edit: This is a conceptual question first and foremost. I can make applications work without knowing this, but I'm trying to learn the concept. I've seen lots of videos with related classes and that makes sense, but when it comes to classes wrapping around other classes, I can't seem to grasp where things should be instantiated/passed around. =-=-=-=-=-=-= Question: Let's say I have a simple page that loads data from a table, manipulates the result and displays it. Simple. I'm going to use '=' for instantiating a class and '-' for passing a class in using constructor injection. It seems to me that the database has to be passed from one end of the application to the other which doesn't seem right. Here's how I would do it if I wanted to separate concerns: index =>Controller =>Model Layer =>Database =>DAO->Database I have this rule in my head that says I'm not supposed to create objects inside other objects. So what do I do with the Database? Or even the Model for that matter? I'm obviously missing something so basic about this. I would love a simplified example so that I can move forward in my code. I feel really hamstrung by this.

    Read the article

  • How can I use "Dependency Injection" in simple php functions, and should I bother?

    - by Tchalvak
    I hear people talking about dependency injection and the benefit of it all the time, but I don't really understand it. I'm wondering if it's a solution to the "I pass database connections as arguments all the time" problem. I tried reading wikipedia's entry on it, but the example is written in Java so I don't solidly understand the difference it is trying to make clear. ( http://en.wikipedia.org/wiki/Dependency_injection ). I read this dependency-injection-in-php article ( http://www.potstuck.com/2009/01/08/php-dependency-injection/ ), and it seems like the objective is to not pass dependencies to an object directly, but to cordon off the creation of an object along with the creation of it's dependencies. I'm not sure how to apply that in a using php functions context, though. Additionally, is the following Dependency Injection, and should I bother trying to do dependency injection in a functional context? Version 1: (the kind of code that I create, but don't like, every day) function get_data_from_database($database_connection){ $data = $database_connection->query('blah'); return $data; } Version 2: (don't have to pass a database connection, but perhaps not dependency injection?) function get_database_connection(){ static $db_connection; if($db_connection){ return $db_connection; } else { // create db_connection ... } } function get_data_from_database(){ $conn = get_database_connection(); $data = $conn->query('blah'); return $data; } $data = get_data_from_database(); Version 3: (the creation of the "object"/data is separate, and the database code is still, so perhaps this would count as dependency injection?) function factory_of_data_set(){ static $db_connection; $data_set = null; $db_connection = get_database_connection(); $data_set = $db_connection->query('blah'); return $data_set; } $data = factory_of_data_set(); Anyone have a good resource or just insight that makes the method and benefit -crystal- clear?

    Read the article

  • Jboss AS 7 - Dependency Injection

    - by Nic Willemse
    Im attempting to make use of dependency injection in Jboss AS 7 and im having huge difficulties. I have setup a EAR which contains both a EJB jar and a war. The war contains a richfaces web app. Im attempting to inject an EJB from the ejb jar into a faces managed bean with the code below : public class UserController { @EJB(mappedName="UserService") private UserFacadeService userService; public String getService(){ if(userService == null){ however when i deploy jboss puts the error in the console : rolled back with failure message {"Services with missing/unavailable dependencies" => ["jboss.deployment.subunit.\"GoodByeJohnEAR.ear\".\"GoodByeJohnWeb-1.0-SNAPSHOT.war\".component.\"managed-bean.za.co.gbj.UserController\".START missing [ jboss.naming.context.java.module.GoodByeJohnEAR.\"GoodByeJohnWeb-1.0-SNAPSHOT\".\"env/za.co.gbj.UserController/userService\" ]","jboss.deployment.subunit.\"GoodByeJohnEAR.ear\".\"GoodByeJohnWeb-1.0-SNAPSHOT.war\".jndiDependencyService missing [ jboss.naming.context.java.module.GoodByeJohnEAR.\"GoodByeJohnWeb-1.0-SNAPSHOT\".\"env/za.co.gbj.UserController/userService\" ]","jboss.naming.context.java.module.GoodByeJohnEAR.\"GoodByeJohnWeb-1.0-SNAPSHOT\".\"env/za.co.gbj.UserController/userService\".jboss.deployment.subunit.\"GoodByeJohnEAR.ear\".\"GoodByeJohnWeb-1.0-SNAPSHOT.war\".module.GoodByeJohnEAR.\"GoodByeJohnWeb-1.0-SNAPSHOT\".2 missing [ jboss.naming.context.java.module.GoodByeJohnEAR.\"GoodByeJohnWeb-1.0-SNAPSHOT\".env/UserService ]"]} 09:03:50,576 INFO [org.jboss.as.server.deployment] (MSC service thread 1-8) Starting deployment of "GoodByeJohnEAR.ear" 09:03:50,670 INFO [org.jboss.as.server.deployment] (MSC service thread 1-3) Starting deployment of "GoodByeJohnWeb-1.0-SNAPSHOT.war" 09:03:50,670 INFO [org.jboss.as.server.deployment] (MSC service thread 1-8) Starting deployment of "GoodByeJohnEJB-1.0-SNAPSHOT.jar" 09:03:51,367 WARN [org.jboss.as.server.deployment.service-loader] (MSC service thread 1-2) Encountered invalid class name "com.sun.faces.vendor.Tomcat6InjectionProvider:org.apache.catalina.util.DefaultAnnotationProcessor" for service type "com.sun.faces.spi.injectionprovider" 09:03:51,367 WARN [org.jboss.as.server.deployment.service-loader] (MSC service thread 1-2) Encountered invalid class name "com.sun.faces.vendor.Jetty6InjectionProvider:org.mortbay.jetty.plus.annotation.InjectionCollection" for service type "com.sun.faces.spi.injectionprovider" 09:03:51,375 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-8) JNDI bindings for session bean named UserFacadeBean in deployment unit subdeployment "GoodByeJohnEJB-1.0-SNAPSHOT.jar" of deployment "GoodByeJohnEAR.ear" are as follows: java:global/GoodByeJohnEAR/GoodByeJohnEJB-1.0-SNAPSHOT/UserFacadeBean!za.co.gbj.UserFacadeService java:app/GoodByeJohnEJB-1.0-SNAPSHOT/UserFacadeBean!za.co.gbj.UserFacadeService java:module/UserFacadeBean!za.co.gbj.UserFacadeService java:global/GoodByeJohnEAR/GoodByeJohnEJB-1.0-SNAPSHOT/UserFacadeBean java:app/GoodByeJohnEJB-1.0-SNAPSHOT/UserFacadeBean java:module/UserFacadeBean 09:03:51,406 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-4) JNDI bindings for session bean named UserFacadeBean in deployment unit subdeployment "GoodByeJohnWeb-1.0-SNAPSHOT.war" of deployment "GoodByeJohnEAR.ear" are as follows: java:global/GoodByeJohnEAR/GoodByeJohnWeb-1.0-SNAPSHOT/UserFacadeBean!za.co.gbj.UserFacadeService java:app/GoodByeJohnWeb-1.0-SNAPSHOT/UserFacadeBean!za.co.gbj.UserFacadeService java:module/UserFacadeBean!za.co.gbj.UserFacadeService java:global/GoodByeJohnEAR/GoodByeJohnWeb-1.0-SNAPSHOT/UserFacadeBean java:app/GoodByeJohnWeb-1.0-SNAPSHOT/UserFacadeBean java:module/UserFacadeBean 09:03:51,577 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 1) Service status report New missing/unsatisfied dependencies: service jboss.naming.context.java.module.GoodByeJohnEAR."GoodByeJohnWeb-1.0-SNAPSHOT".env/UserService (missing) service jboss.naming.context.java.module.GoodByeJohnEAR."GoodByeJohnWeb-1.0-SNAPSHOT"."env/za.co.gbj.UserController/userService" (missing) Please assist!

    Read the article

  • Dependency injection in constructor, method or just use a static class instead?

    - by gaetanm
    What is the best between: $dispatcher = new Dispatcher($request); $dispatcher->dispatch(); and $dispatcher = new Dispatcher(); $dispatcher->dispatch($request); or even Dispatcher::dispatch($request); Knowing that only one method of this class uses the $request instance. I naturally tend to the last solution because the class have no other states, but by I feel that it may not be the best OOP solution.

    Read the article

  • How to do dependency Injection and conditional object creation based on type?

    - by Pradeep
    I have a service endpoint initialized using DI. It is of the following style. This end point is used across the app. public class CustomerService : ICustomerService { private IValidationService ValidationService { get; set; } private ICustomerRepository Repository { get; set; } public CustomerService(IValidationService validationService,ICustomerRepository repository) { ValidationService = validationService; Repository = repository; } public void Save(CustomerDTO customer) { if (ValidationService.Valid(customer)) Repository.Save(customer); } Now, With the changing requirements, there are going to be different types of customers (Legacy/Regular). The requirement is based on the type of the customer I have to validate and persist the customer in a different way (e.g. if Legacy customer persist to LegacyRepository). The wrong way to do this will be to break DI and do somthing like public void Save(CustomerDTO customer) { if(customer.Type == CustomerTypes.Legacy) { if (LegacyValidationService.Valid(customer)) LegacyRepository.Save(customer); } else { if (ValidationService.Valid(customer)) Repository.Save(customer); } } My options to me seems like DI all possible IValidationService and ICustomerRepository and switch based on type, which seems wrong. The other is to change the service signature to Save(IValidationService validation, ICustomerRepository repository, CustomerDTO customer) which is an invasive change. Break DI. Use the Strategy pattern approach for each type and do something like: validation= CustomerValidationServiceFactory.GetStratedgy(customer.Type); validation.Valid(customer) but now I have a static method which needs to know how to initialize different services. I am sure this is a very common problem, What is the right way to solve this without changing service signatures or breaking DI?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >