Search Results

Search found 88696 results on 3548 pages for 'code injection'.

Page 8/3548 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • SQL Injection with Plain-Vanilla NHibernate

    - by James D
    Hello, Plain-vanilla NHibernate setup, eg, no fluent NHibernate, no HQL, nothing except domain objects and NHibernate mapping files. I load objects via: _lightSabers = session.CreateCriteria(typeof(LightSaber)).List<LightSaber>(); I apply raw user input directly to one property on the "LightSaber" class: myLightSaber.NameTag = "Raw malicious text from user"; I then save the LightSaber: session.SaveOrUpdate(myLightSaber); Everything I've seen says that yes, under this situation you are immune to SQL injection, because of the way NHibernate parameterizes and escapes the queries under the hood. However, I'm also a relative NHibernate beginner so I wanted to double-check. *waves hand* these aren't the droids you're looking for. Thanks!

    Read the article

  • Prevent SQL injection from form-generated SQL.

    - by Markos Fragkakis
    Hi all, I have a search table where user will be able to filter results with a filter of the type: Field [Name], Value [John], Remove Rule Field [Surname], Value [Blake], Remove Rule Field [Has Children], Value [Yes], Remove Rule Add Rule So the user will be able to set an arbitrary set of filters, which will result essentially in a completely dynamic WHERE clause. In the future I will also have to implement more complicated logical expressions, like Where (name=John OR name=Nick) AND (surname=Blake OR surname=Bourne), Of all 10 fields the user may or may not filter by, I don't know how many and which filters the user will set. So, I cannot use a prepared statement (which assumes that at least we know the fields in the WHERE clause). This is why prepared statements are unfortunately out of the question, I have to do it with plain old, generated SQL. What measures can I take to protect the application from SQL Injection (REGEX-wise or any other way)?

    Read the article

  • Potential for SQL injection here?

    - by Matt Greer
    This may be a really dumb question but I figure why not... I am using RIA Services with Entity Framework as the back end. I have some places in my app where I accept user input and directly ask RIA Services (and in turn EF and in turn my database) questions using their data. Do any of these layers help prevent security issues or should I scrub my data myself? For example, whenever a new user registers with the app, I call this method: [Query] public IEnumerable<EmailVerificationResult> VerifyUserWithEmailToken(string token) { using (UserService userService = new UserService()) { // token came straight from the user, am I in trouble here passing it directly into // my DomainService, should I verify the data here (or in UserService)? User user = userService.GetUserByEmailVerificationToken(token); ... } } (and whether I should be rolling my own user verification system is another issue altogether, we are in the process of adopting MS's membership framework. I'm more interested in sql injection and RIA services in general)

    Read the article

  • Prevent sqlite INJECTION ATTACKS on your own iPhone?

    - by Bonnie
    I always take precautions regarding SQL INJECTION ATTACKS when data is saved between someone's iPhone and a remote database on the cloud. But is it also necessary to do the same... when just saving data (using sqlite) from someone's cell phone, to a database that's just on their own phone? What's the worse they can do? Delete their own data (or tables) on their own phone? (If they really try hard enough.) Thanks.

    Read the article

  • JSR-303 dependency injection and Hibernate

    - by Jam
    Spring 3.0.2, Hibernate 3.5.0, Hibernate-Validator 4.0.2.GA I am trying to inject Spring dependencies into a ConstraintValidator using: @PersistenceContext private EntityManager entityManager; I have configured the application context with: <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/> Which, according to the Spring documentation, should allow “custom ConstraintValidators to benefit from dependency injection like any other Spring bean” Within the debugger I can see Spring calling getBean to create the ConstraintValidator. Later when flush triggers the preInsert, a different ConstraintValidator is created and called. The problem is the EntityManager is null within this new ConstraintValidator. I’ve tried injecting other dependencies within the ConstraintValidator and these are always null. Does anyone know if it is possible to inject dependencies into a ConstraintValidator?

    Read the article

  • Why JPA injection not works on @PersistentUnit

    - by Dewfy
    Hello colleagues! It is continues of question ( http://stackoverflow.com/questions/2570976/struts-2-bean-is-not-created ) I'm using struts2 + toplink in my very simple web application under Tomcat. On the page I would like use iteration tag. That is why I've declared some factory (SomeFactory) that resolves collection of entities (Entity). Per article: http://download-uk.oracle.com/docs/cd/B32110_01/web.1013/b28221/usclient005.htm#CIHCEHHG the only thing I need is declaration: @PersistenceContext(unitName="name_in_persistence_xml") public class SomeFactory { @PersistenceUnit(unitName="name_in_persistence_xml") EntityManagerFactory emf; public EntityManager getEntityManager() { assert(emf != null); //HERE every time it is null return emf.createEntityManager(); } public Collection<Entity> getAll() { return getEntityManager().createNamedQuery("Entity.findAll").getResultList(); } } What is wrong? May be i miss something in web.xml? How to pre-init toplink for web application to allow injection happen?

    Read the article

  • Passing ASP.NET User by Dependency Injection

    - by UpTheCreek
    In my web application I have various components that need to access the currently authenticated user (HttpContext.User). There are two obvious ways a component can access this: 1) Accessing getting the User from HttpContext.Current 2) Passing the user around in constructors Is not ideal because it makes testing difficult and ties application components to web concerns, when they really shouldn't know about it. Is just messy and complicates everything. So I've been thinking about passing in the current user (or perhaps just the name/id) to any component that needs it using an IoC container (via dependency injection). Is anyone using this technique to supply the current ASP.NET user to parts of the application? Or, Does this sound like a sensible approach? I would like know how this has worked out for people. Thanks

    Read the article

  • 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

  • Tips on a tool to measure code quality?

    - by Cristi Diaconescu
    I'm looking for a tool that can provide code quality metrics. For instance it could report very long functions (spaghetti code) very complex classes (which could contain do-it-all code) ... While we're on the (subjective:-) subject of code quality, what other code metrics would you suggest? I'm targetting C#/.NET code, but I'm sure this could extend to most programming languages.

    Read the article

  • Visual Studio 2013 Static Code Analysis in depth: What? When and How?

    - by Hosam Kamel
    In this post I'll illustrate in details the following points What is static code analysis? When to use? Supported platforms Supported Visual Studio versions How to use Run Code Analysis Manually Run Code Analysis Automatically Run Code Analysis while check-in source code to TFS version control (TFSVC) Run Code Analysis as part of Team Build Understand the Code Analysis results & learn how to fix them Create your custom rule set Q & A References What is static Rule analysis? Static Code Analysis feature of Visual Studio performs static code analysis on code to help developers identify potential design, globalization, interoperability, performance, security, and a lot of other categories of potential problems according to Microsoft's rules that mainly targets best practices in writing code, and there is a large set of those rules included with Visual Studio grouped into different categorized targeting specific coding issues like security, design, Interoperability, globalizations and others. Static here means analyzing the source code without executing it and this type of analysis can be performed through automated tools (like Visual Studio 2013 Code Analysis Tool) or manually through Code Review which already supported in Visual Studio 2012 and 2013 (check Using Code Review to Improve Quality video on Channel9) There is also Dynamic analysis which performed on executing programs using software testing techniques such as Code Coverage for example. When to use? Running Code analysis tool at regular intervals during your development process can enhance the quality of your software, examines your code for a set of common defects and violations is always a good programming practice. Adding that Code analysis can also find defects in your code that are difficult to discover through testing allowing you to achieve first level quality gate for you application during development phase before you release it to the testing team. Supported platforms .NET Framework, native (C and C++) Database applications. Support Visual Studio versions All version of Visual Studio starting Visual Studio 2013 (except Visual Studio Test Professional) check Feature comparisons Create and modify a custom rule set required Visual Studio Premium or Ultimate. How to use? Code Analysis can be run manually at any time from within the Visual Studio IDE, or even setup to automatically run as part of a Team Build or check-in policy for Team Foundation Server. Run Code Analysis Manually To run code analysis manually on a project, on the Analyze menu, click Run Code Analysis on your project or simply right click on the project name on the Solution Explorer choose Run Code Analysis from the context menu Run Code Analysis Automatically To run code analysis each time that you build a project, you select Enable Code Analysis on Build on the project's Property Page Run Code Analysis while check-in source code to TFS version control (TFSVC) Team Foundation Version Control (TFVC) provides a way for organizations to enforce practices that lead to better code and more efficient group development through Check-in policies which are rules that are set at the team project level and enforced on developer computers before code is allowed to be checked in. (This is available only if you're using Team Foundation Server) Require permissions on Team Foundation Server: you must have the Edit project-level information permission set to Allow typically your account must be part of Project Administrators, Project Collection Administrators, for more information about Team Foundation permissions check http://msdn.microsoft.com/en-us/library/ms252587(v=vs.120).aspx In Team Explorer, right-click the team project name, point to Team Project Settings, and then click Source Control. In the Source Control dialog box, select the Check-in Policy tab. Click Add to create a new check-in policy. Double-click the existing Code Analysis item in the Policy Type list to change the policy. Check or Uncheck the policy option based on the configurations you need to perform as illustrated below: Enforce check-in to only contain files that are part of current solution: code analysis can run only on files specified in solution and project configuration files. This policy guarantees that all code that is part of a solution is analyzed. Enforce C/C++ Code Analysis (/analyze): Requires that all C or C++ projects be built with the /analyze compiler option to run code analysis before they can be checked in. Enforce Code Analysis for Managed Code: Requires that all managed projects run code analysis and build before they can be checked in. Check Code analysis rule set reference on MSDN What is Rule Set? Rule Set is a group of code analysis rules like the example below where Microsoft.Design is the rule set name where "Do not declare static members on generic types" is the code analysis rule Once you configured the Analysis rule the policy will be enabled for all the team member in this project whenever a team member check-in any source code to the TFSVC the policy section will highlight the Code Analysis policy as below TFS is a very extensible platform so you can simply implement your own custom Code Analysis Check-in policy, check this link for more details http://msdn.microsoft.com/en-us/library/dd492668.aspx but you have to be aware also about compatibility between different TFS versions check http://msdn.microsoft.com/en-us/library/bb907157.aspx Run Code Analysis as part of Team Build With Team Foundation Build (TFBuild), you can create and manage build processes that automatically compile and test your applications, and perform other important functions. Code Analysis can be enabled in the Build Definition file by selecting the correct value for the build process parameter "Perform Code Analysis" Once configure, Kick-off your build definition to queue a new build, Code Analysis will run as part of build workflow and you will be able to see code analysis warning as part of build report Understand the Code Analysis results & learn how to fix them Now after you went through Code Analysis configurations and the different ways of running it, we will go through the Code Analysis result how to understand them and how to resolve them. Code Analysis window in Visual Studio will show all the analysis results based on the rule sets you configured in the project file properties, let's dig deep into what each result item contains: 1 Check ID The unique identifier for the rule. CheckId and Category are used for in-source suppression of a warning.       2 Title The title of warning message       3 Description A description of the problem or suggested fix 4 File Name File name and the line of code number which violate the code analysis rule set 5 Category The code analysis category for this error 6 Warning /Error Depend on how you configure it in the rule set the default is Warning level 7 Action Copy: copy the warning information to the clipboard Create Work Item: If you're connected to Team Foundation Server you can create a work item most probably you may create a Task or Bug and assign it for a developer to fix certain code analysis warning Suppress Message: There are times when you might decide not to fix a code analysis warning. You might decide that resolving the warning requires too much recoding in relation to the probability that the issue will arise in any real-world implementation of your code. Or you might believe that the analysis that is used in the warning is inappropriate for the particular context. You can suppress individual warnings so that they no longer appear in the Code Analysis window. Two options available: In Source inserts a SuppressMessage attribute in the source file above the method that generated the warning. This makes the suppression more discoverable. In Suppression File adds a SuppressMessage attribute to the GlobalSuppressions.cs file of the project. This can make the management of suppressions easier. Note that the SuppressMessage attribute added to GlobalSuppression.cs also targets the method that generated the warning. It does not suppress the warning globally.       Visual Studio makes it very easy to fix Code analysis warning, all you have to do is clicking on the Check Id hyperlink if you are not aware how to fix the warring and you'll be directed to MSDN online or local copy based on the configuration you did while installing Visual Studio and you will find all the information about the warring including how to fix it. Create a Custom Code Analysis Rule Set The Microsoft standard rule sets provide groups of rules that are organized by function and depth. For example, the Microsoft Basic Design Guidelines Rules and the Microsoft Extended Design Guidelines Rules contain rules that focus on usability and maintainability issues, with added emphasis on naming rules in the Extended rule set, you can create and modify a custom rule set to meet specific project needs associated with code analysis. To create a custom rule set, you open one or more standard rule sets in the rule set editor. Create and modify a custom rule set required Visual Studio Premium or Ultimate. You can check How to: Create a Custom Rule Set on MSDN for more details http://msdn.microsoft.com/en-us/library/dd264974.aspx Q & A Visual Studio static code analysis vs. FxCop vs. StyleCpp http://www.excella.com/blog/stylecop-vs-fxcop-difference-between-code-analysis-tools/ Code Analysis for SharePoint Apps and SPDisposeCheck? This post lists some of the rule set you can run specifically for SharePoint applications and how to integrate SPDisposeCheck as well. Code Analysis for SQL Server Database Projects? This post illustrate how to run static code analysis on T-SQL through SSDT ReSharper 8 vs. Visual Studio 2013? This document lists some of the features that are provided by ReSharper 8 but are missing or not as fully implemented in Visual Studio 2013. References A Few Billion Lines of Code Later: Using Static Analysis to Find Bugs in the Real World http://cacm.acm.org/magazines/2010/2/69354-a-few-billion-lines-of-code-later/fulltext What is New in Code Analysis for Visual Studio 2013 http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/03/what-is-new-in-code-analysis-for-visual-studio-2013.aspx Analyze the code quality of Windows Store apps using Visual Studio static code analysis http://msdn.microsoft.com/en-us/library/windows/apps/hh441471.aspx [Hands-on-lab] Using Code Analysis with Visual Studio 2012 to Improve Code Quality http://download.microsoft.com/download/A/9/2/A9253B14-5F23-4BC8-9C7E-F5199DB5F831/Using%20Code%20Analysis%20with%20Visual%20Studio%202012%20to%20Improve%20Code%20Quality.docx Originally posted at "Hosam Kamel| Developer & Platform Evangelist" http://blogs.msdn.com/hkamel

    Read the article

  • How can I promote clean coding at my workplace?

    - by Michael
    I work with a lot of legacy Java and RPG code on an internal company application. As you might expect, a lot of the code is written in many different styles, and often is difficult to read because of poorly named variables, inconsistent formatting, and contradictory comments (if they're there at all). Also, a good amount of code is not robust. Many times code is pushed to production quickly by the more experienced programmers, while code by newer programmers is held back by "code reviews" that IMO are unsatisfactory. (They usually take the form of, "It works, must be ok," than a serious critique of the code.) We have a fair number of production issues, which I feel could be lessened by giving more thought to the original design and testing. I have been working for this company for about 4 months, and have been complimented on my coding style a couple of times. My manager is also a fan of cleaner coding than is the norm. Is it my place to try to push for better style and better defensive coding, or should I simply code in the best way I can, and hope that my example will help others see how cleaner, more robust code (as well as aggressive refactoring) will result in less debugging and change time?

    Read the article

  • How should Code Review be Carried Out?

    - by Graviton
    My previous question has to do with how to advance code review among the developers. Here I am interested in how the code review session should be carried out, so that both the reviewer and reviewed are feeling comfortable about it. I have done some code review before, but the experience sucks big time. My previous manager would come to us-- on an ad hoc basis-- and tell us to explain our code to him. Since he wasn't very familiar with the code base, I spent a huge amount of times explaining just the most basic structure of my code to him. This took a long time and by the time we were done, we were both exhausted. Then he would raise issues with my code. Most issues he raised were cosmetic in nature ( e.g, don't use region for this code block, change the variable name from xxx to yyy even though the later makes even less sense, and so on). We did this a few rounds, and the review session didn't derive much benefits for us, and we stopped. What do you have to do, in order to make code review a natural, enjoyable, thought stimulating, bug-fixing and mutual-learning experience?

    Read the article

  • Advancing Code Review and Unit Testing Practice

    - by Graviton
    As a team lead managing a group of developers with no experience ( and see no need) in code review and unit testing, how can you advance code review and unit testing practice? How are you going to create a way so that code review and unit testing to naturally fit into the developer's flow? One of the resistance of these two areas is that "we are always tight on dateline, so no time for code review and unit testing". Another resistance for code review is that we currently don't know how to do it. Should we review the code upon every check-in, or review the code at a specified date?

    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

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >