Search Results

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

Page 24/53 | < Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >

  • How to use StructureMap to inject repository classes to the controller?

    - by Lorenzo
    In the current application I am working on I have a custom ControllerFactory class that create a controller and automatically sets the Elmah ErrorHandler. public class BaseControllerFactory : DefaultControllerFactory { public override IController CreateController( RequestContext requestContext, string controllerName ) { var controller = base.CreateController( requestContext, controllerName ); var c = controller as Controller; if ( c != null ) { c.ActionInvoker = new ErrorHandlingActionInvoker( new HandleErrorWithElmahAttribute() ); } return controller; } protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType ) { try { if ( ( requestContext == null ) || ( controllerType == null ) ) return base.GetControllerInstance( requestContext, controllerType ); return (Controller)ObjectFactory.GetInstance( controllerType ); } catch ( StructureMapException ) { System.Diagnostics.Debug.WriteLine( ObjectFactory.WhatDoIHave() ); throw new Exception( ObjectFactory.WhatDoIHave() ); } } } I would like to use StructureMap to inject some code in my controllers. For example I would like to automatically inject repository classes in them. I have already created my repository classes and also I have added a constructor to the controller that receive the repository class public FirmController( IContactRepository contactRepository ) { _contactRepository = contactRepository; } I have then registered the type within StructureMap ObjectFactory.Initialize( x => { x.For<IContactRepository>().Use<MyContactRepository>(); }); How should I change the code in the CreateController method to have the IContactRepository concrete class injected in the FirmController? EDIT: I have changed the BaseControllerFactory to use Structuremap. But I get an exception on the line return (Controller)ObjectFactory.GetInstance( controllerType ); Any hint?

    Read the article

  • Learning to implement DIC in MVC

    - by Tom
    I am learning to apply DIC to MVC project. So, I have sketched this DDD-ish DIC-ready-ish layout to my best understanding. I have read many blogs articles wikis for the last few days. However, I am not confident about implementing it correctly. Could you please demonstrate to me how to put them into DIC the proper way? I prefer Ninject or Windsor after all the readings, but anyDIC will do as long as I can get the correct idea how to do it. Web controller... public class AccountBriefingController { //create private IAccountServices accountServices { get; set; } public AccountBriefingController(IAccountServices accsrv) accountServices = accsrv; } //do work public ActionResult AccountBriefing(string userid, int days) { //get days of transaction records for this user BriefingViewModel model = AccountServices.GetBriefing(userid, days); return View(model); } } View model ... public class BriefingViewModel { //from user repository public string UserId { get; set; } public string AccountNumber {get; set;} public string FirstName { get; set; } public string LastName { get; set; } //from account repository public string Credits { get; set; } public List<string> Transactions { get; set; } } Service layer ... public interface IAccountServices { BriefingViewModel GetBriefing(); } public class AccountServices { //create private IUserRepository userRepo {get; set;} private IAccountRepository accRepo {get; set;} public AccountServices(UserRepository ur, AccountRepository ar) { userRepo = ur; accRepo = ar; } //do work public BriefingViewModel GetBriefing(string userid, int days) { var model = new BriefingViewModel(); //<---is that okay to new a model here?? var user = userRepo.GetUser(userid); if(user != null) { model.UserId = userid; model.AccountNumber = user.AccountNumber; model.FirstName = user.FirstName; model.LastName = user.LastName; //account records model.Credits = accRepo.GetUserCredits(userid); model.Transactions = accRepo.GetUserTransactions(userid, days); } return model; } } Domain layer and data models... public interface IUserRepository { UserDataModel GetUser(userid); } public interface IAccountRepository { List<string> GetUserTransactions(userid, days); int GetUserCredits(userid); } // Entity Framework DBContext goes under here Please point out if my implementation is wrong, e.g.I can feel in AccountServices-GetBriefing - new BriefingViewModel() seems wrong to me, but I don't know how to fit the stud into DIC? Thank you very much for your help!

    Read the article

  • Reinject dependencies of a freshly deserialized object

    - by NathanE
    If a program has literally just deserialized an object (doesn't really matter how, but just say BinaryFormatter was used). What is a good design to use for re-injecting the dependencies of this object? Is there a common pattern for this? I suppose I would need to wrap the Deserialize() method up to act as a factory inside the container. Thanks!

    Read the article

  • castle windsor container not wiring properties correctly

    - by Damian
    I have a class that i want to instantiate thru castle in configuration. public class MyMappings : IMappings { Mapping FirstMapping { get; set; } Mapping SecondMapping { get; set; } OtherType ThirdMapping { get; set; } OtherType FourthMapping { get; set; } Mapping FifthMapping { get; set; } OtherType SixMapping { get; set; } } In my configuration i have the following: ${anothercomponentIDForCompomentOftypeMapping} The problem i am facing is that is assigning the same value to all properties of the same type, completly ignoring the name of the parameter. This properties are optional, i just want to initialize the value for one of them. Thanks,

    Read the article

  • Ninject: How do I inject into a class library ?

    - by DennyDotNet
    To start I'm using Ninject 1.5. I have two projects: Web project and a Class library. My DI configuration is within the Web project. Within my class library I have the following defined: public interface ICacheService<T> { string Identifier { get; } T Get(); void Set( T objectToCache, TimeSpan timeSpan ); bool Exists(); } And then a concrete class called CategoryCacheService. In my web project I bind the two: Bind( typeof( ICacheService<List<Category>> ) ).To( typeof(CategoryCacheService)).Using<SingletonBehavior>(); In my class library I have extension methods for the HtmlHelper class, for example: public static class Category { [Inject] public static ICacheService Categories { get; set; } public static string RenderCategories(this HtmlHelper htmlHelper) { var c = Categories.Get(); return string.Join(", ", c.Select(s = s.Name).ToArray()); } } I've been told that you cannot inject into static properties, instead I should use Kernel.Get<() - However... Since the code above is in a class library I don't have access to the Kernel. How can I get the Kernel from this point or is there a better way of doing this? Thanks!

    Read the article

  • How do I bind Different Interfaces using Google Guice?

    - by kunjaan
    Do I need to create a new module with the Interface bound to a different implementation? Chef newChef = Guice.createInjector(Stage.DEVELOPMENT, new Module() { @Override public void configure(Binder binder) { binder.bind(FortuneService.class).to(FortuneServiceImpl.class); } }).getInstance(Chef.class); Chef newChef2 = Guice.createInjector(Stage.DEVELOPMENT, new Module() { @Override public void configure(Binder binder) { binder.bind(FortuneService.class).to(FortuneServiceImpl2.class); } }).getInstance(Chef.class); I cannot touch the Chef Class nor the Interfaces. I am just a client binding to Chef's FortuneService to different Interfaces at runtime.

    Read the article

  • Automatic release of objects when using Castle Windsor

    - by MotoSV
    Hi, I'm starting a new project and I'm looking into using a dependency container (Castle Windsor) to help when it comes to unit testing. One of the things that is a little frustrating is that after I've finished using an object I have to tell the container to "release" the object. I understand the reasoning behind doing this, but it's still cumbersome to have to remember to do this. So, my question is, is there a way I can make the "releasing" of an object automatic so I don't have to remember to release it? Kind Regards Michael

    Read the article

  • T4 Template Interception

    - by JeffN825
    I'm wondering if anyone out there knows of any T4 template based method interception systems? We are beginning to write mobile applications (currently with MonoTouch for IOS). We have a very nice core set of DI/IoC functionality and I'd like to leverage this in development for the new platform. Since runtime code generation Reflection.Emit is not supported, I'm hoping to use T4 templates to implement the dynamic interception functionality (+ TinyIoC as a container for resolution). We are currently using Castle Windsor (and intend to continue doing so for our SL and full .NET development), but all of the Windsor specific ties are completely encapsulated, so given a suitable T4 solution, it shouldn't be hard to implement an adapter that uses a T4 based implementation instead of Windsor.

    Read the article

  • Is scala's cake pattern possible with parametrized components?

    - by Nicolas
    Parametrized components work well with the cake pattern as long as you are only interested in a unique component for each typed component's, example: trait AComponent[T] { val a:A[T] class A[T](implicit mf:Manifest[T]) { println(mf) } } class App extends AComponent[Int] { val a = new A[Int]() } new App Now my application requires me to inject an A[Int] and an A[String], obviously scala's type system doesn't allow me to extends AComponent twice. What is the common practice in this situation ?

    Read the article

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

    - by SharePoint Newbie
    Hi, I have the following classes: class Repository : IRepository class ReadOnlyRepository : Repository abstract class Command abstract CommandImpl : Command { public CommandImpl(Repository repository){} } class Service { public Service (Command[] commands){} } I register them in code as follows: var container = new Container("WindsorCOntainer.config"); var container = new WindsorContainer(new XmlInterpreter("WindsorConfig.xml")); container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel)); container.AddComponent("repository", typeof(RentServiceRepository)); container.Resolve<RentServiceRepository>(); container.AddComponent("command", typeof(COmmandImpl)); container.AddComponent("rentService", typeof (RentService)); container.Resolve<RentService>(); // Fails here I get the message that "RentService is waiting for dependency commands" What am I doing wrong? Thanks,

    Read the article

  • How do I create different Objects using Google Guice?

    - by kunjaan
    I have a Module which binds an Interface to a particular implementation. I use that module to create an object. How do I create a different kind of object with the the interface bound to a different implementation? Do I need to create a new module with the Interface bound to a different implementation?

    Read the article

  • Is this a problem typically solved with IOC?

    - by Dirk
    My current application allows users to define custom web forms through a set of admin screens. it's essentially an EAV type application. As such, I can't hard code HTML or ASP.NET markup to render a given page. Instead, the UI requests an instance of a Form object from the service layer, which in turn constructs one using a several RDMBS tables. Form contains the kind of classes you would expect to see in such a context: Form= IEnumerable<FormSections>=IEnumerable<FormFields> Here's what the service layer looks like: public class MyFormService: IFormService{ public Form OpenForm(int formId){ //construct and return a concrete implementation of Form } } Everything works splendidly (for a while). The UI is none the wiser about what sections/fields exist in a given form: It happily renders the Form object it receives into a functional ASP.NET page. A few weeks later, I get a new requirement from the business: When viewing a non-editable (i.e. read-only) versions of a form, certain field values should be merged together and other contrived/calculated fields should are added. No problem I say. Simply amend my service class so that its methods are more explicit: public class MyFormService: IFormService{ public Form OpenFormForEditing(int formId){ //construct and return a concrete implementation of Form } public Form OpenFormForViewing(int formId){ //construct and a concrete implementation of Form //apply additional transformations to the form } } Again everything works great and balance has been restored to the force. The UI continues to be agnostic as to what is in the Form, and our separation of concerns is achieved. Only a few short weeks later, however, the business puts out a new requirement: in certain scenarios, we should apply only some of the form transformations I referenced above. At this point, it feels like the "explicit method" approach has reached a dead end, unless I want to end up with an explosion of methods (OpenFormViewingScenario1, OpenFormViewingScenario2, etc). Instead, I introduce another level of indirection: public interface IFormViewCreator{ void CreateView(Form form); } public class MyFormService: IFormService{ public Form OpenFormForEditing(int formId){ //construct and return a concrete implementation of Form } public Form OpenFormForViewing(int formId, IFormViewCreator formViewCreator){ //construct a concrete implementation of Form //apply transformations to the dynamic field list return formViewCreator.CreateView(form); } } On the surface, this seems like acceptable approach and yet there is a certain smell. Namely, the UI, which had been living in ignorant bliss about the implementation details of OpenFormForViewing, must possess knowledge of and create an instance of IFormViewCreator. My questions are twofold: Is there a better way to achieve the composability I'm after? (perhaps by using an IoC container or a home rolled factory to create the concrete IFormViewCreator)? Did I fundamentally screw up the abstraction here?

    Read the article

  • How do I pass dependency to object with Castle Windsor and MS Test?

    - by Nick
    I am trying to use Castle Windsor with MS Test. The test class only seems to use the default constructor. How do I configure Castle to resolve the service in the constructor? Here is the Test Class' constructors: private readonly IWebBrowser _browser; public DepressionSummaryTests() { } public DepressionSummaryTests(IWebBrowser browser) { _browser = browser; } My component in the app config looks like so: <castle> <components> <component id="browser" service="ConversationSummary.IWebBrowser, ConversationSummary" type="ConversationSummary.Browser" /> </components> </castle> Here is my application container: public class ApplicationContainer : WindsorContainer { private static IWindsorContainer container; static ApplicationContainer() { container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle"))); } private static IWindsorContainer Container { get { return container; } } public static IWebBrowser Browser { get { return (IWebBrowser) Container.Resolve("browser"); } } } MS test requires the default constructor. What am I missing? Thanks!

    Read the article

  • Structuremap and creating objects with initial state

    - by Simon
    I have an object which needs a dependency injected into it public class FootballLadder { public FootballLadder(IMatchRepository matchRepository, int round) { // set initial state this.matchRepo = matchRepository; this.round = round; } public IEnumerable<LadderEntry> GetLadderEntries() { // calculate the ladder based on matches retrieved from the match repository // return the calculated ladder } private IMatchRepository matchRepo; private int round; } For arguments sake, lets assume that I can't pass the round parameter into the GetLadderEntries call itself. Using StructureMap, how can I inject the dependency on the IMatchRepository and set the initial state? Or is this one of those cases where struggling against the framework is a sign the code should be refactored?

    Read the article

  • XNA and Ninject: Syntax for dependency arguments?

    - by Rosarch
    I have a class with a public constructor: public MasterEngine(IInputReader inputReader) { this.inputReader = inputReader; graphicsDeviceManager = new GraphicsDeviceManager(this); Components.Add(new GamerServicesComponent(this)); } How can I inject dependencies like graphicsDeviceManager and new GamerServicesComponent while still supplying the argument this?

    Read the article

  • SimpleInjector - Register a type for all it's interfaces

    - by Karl Cassar
    Is it possible to register a type for all it's implementing interfaces? E.g, I have a: public class Bow : IWeapon { #region IWeapon Members public string Attack() { return "Shooted with a bow"; } #endregion } public class HumanFighter { private readonly IWeapon weapon = null; public HumanFighter(IWeapon weapon) { this.weapon = weapon; } public string Fight() { return this.weapon.Attack(); } } [Test] public void Test2b() { Container container = new Container(); container.RegisterSingle<Bow>(); container.RegisterSingle<HumanFighter>(); // this would match the IWeapon to the Bow, as it // is implemented by Bow var humanFighter1 = container.GetInstance<HumanFighter>(); string s = humanFighter1.Fight(); }

    Read the article

  • is right to implement a business logic in the type binding DI framwork?

    - by Martino
    public IRedirect FactoryStrategyRedirect() { if (_PasswordExpired) { return _UpdatePasswordRedirectorFactory.Create(); } else { return _DefaultRedirectorFactory.Create(); } } This strategy factory method can be replaced with type binding and when clause: Bind<IRedirect>.To<UpdatePasswordRedirector>.When(c=> c.kernel.get<SomeContext>().PasswordExpired()) Bind<IRedirect>.To<DefaultRedirector>.When(c=> not c.kernel.get<SomeContext>().PasswordExpired()) I wonder which of the two approaches is the more correct. What are the pros and cons. Especially in the case in which the logic is more complex with more variables to test and more concrete classes to return. is right to implement a business logic in the binding?

    Read the article

  • How to prevent a specific directory from running Php, Html, and Javascript languages?

    - by Emily
    Hi, Let's say i have an image uploader script, i want to prevent the upload directory from executing Php or even html by only showing it as plain text, i've seen this trick in many websites but i don't know how they do it. Briefly, if i upload evil.php to that directory, and i try to access it i will only see a plain text source , No html or php is executed. ( but i still want the images to appear normally ofcourse) I know i can do like that by header("content-type:text/plain"); but that's will not be helpful, because what i want, is to set the content-type:text/plain automatically by the server for every thing outputed from the upload directory except images. Note: i'm running php 5.3.2/Cent OS and the latest cPanel. Thanks

    Read the article

  • Castle Windsor Weak Typed Factory

    - by JeffN825
    In a very very limited number of scenarios, I need to go from an unknown Type (at compile time) to an instance of the object registered for that type. For the most part, I use typed factories and I know the type I want to resolve at compile time...so I inject a Func<IMyType> into a constructor ...but in these limited number of scenarios, in order to avoid a direct call to the container (and thus having to reference Windsor from the library, which is an anti-pattern I'd like to avoid), I need to inject a Func<Type,object>...which I want to internally container.Resolve(type) for the Type parameter of the Func. Does anyone have some suggestions on the easiest/most straightforward way of setting this up? I tried the following, but with this setup, I end up bypassing the regular TypedFactoryFacility altogether which is definitely not what I want: Kernel.Register(Component.For(typeof (Func<Type, object>)).LifeStyle.Singleton.UsingFactoryMethod( (kernel, componentModel, creationContext) => kernel.Resolve(/* not sure what to put here... */))); Thanks in advance for any assistance.

    Read the article

  • Usage patterns/use cases for DI or when to start using it

    - by Fabian
    I'm not sure for which use cases one should to use DI in the application. I know that injecting services like PlaceService or CalculationService etc fits very well but should I also create my domain objects with DI like a User? What is if the User has only one constructor which requires a first and lastname. Is this solveable with DI? Should I use DI to create the instances for Set/List interfaces or is this pure overkill? I use guice primarily.

    Read the article

  • DI: Injecting ActionFilterAttribute implementation (ASP.NET MVC)

    - by Sosh
    I was wondering if it is possible to inject a particular ActionFilterAttribute implementation using a IoC container. For example, imagine you create a TransactionAttribute class [Transaction] You use this to decorate action which should be wrapped in a transaction in the persistence layer. But implementation details of the attribute will be tied to the persistence tech you are using, but strictly speaking, your controller should not know about this, and you might want to swap this out. What I would like to do, is define some kind of TransactionAttribute interface, and then have my IoC inject the correct implantation. So on my actions I only need specify: [Transaction] public ActionResult SomeAction() { .... } ...and the IoC will inject the correct implementation depending on config (eg. something like NHibernateTransactionAttribute, or SomeOtherORMTransactionAttribute). Is this possible? Has anyone done it?

    Read the article

  • Struts1 and Spring wiring question

    - by Dev er dev
    Recently I had a pleasure of working again on Struts 1.1 application. It uses Spring 2.5, but not for actions. I would like to hook it up to use Spring as DI for Struts Actions also, as it would make my life a loot easier. I found out DelegatingRequestProcessor could be used for this purpose, at least according to documentation, but seems it has been deprecated as of Spring 3.0. Switching to the new version of Struts is not an option. Does anyone have better idea then starting to use deprecated stuff?

    Read the article

  • Should an object be fully complete before injected as a dependency?

    - by Hans
    This is an extension of this question: http://stackoverflow.com/questions/3027082/understanding-how-to-inject-object-dependencies. Since it is a bit different, I wanted to separate them, to make it, hopefully, easier to answer. Also, this is not a real system, just a simplified example that I thought we'd all be familiar with. TIA. : DB threads: thread_id, thread_name, etc posts: post_id, thread_id, post_name, post_contents, post_date, post_user_id, etc Overview Basically I'm looking at the most maintainable way to load $post_id and have it cascade and load the other things I want to know about and I'm trying to keep the controller skinny. BUT: I'm ending up with too many dependencies to inject I'm passing in initialized but empty objects I want to limit how many parameters I am passing around I could inject $post(-many) into $thread(one<-), but on that page I'm not looking at a thread, I'm looking at a post I could combine/inject them into a new object Detail If I am injecting an object into another, is it best to have it fully created first? I'm trying to limit how many parameters I have to pass in to a page, but I end up with a circle. // 1, empty object injected via constructor $thread = new Thread; $post = new Post($thread); // $thread is just an empty object $post->load($post_id); // I could now do something like $post->get('thread_id') to get everything I want in $post // 2, complete object injected via constructor $thread = new Thread; $thread->load($thread_id); // this page would have to have passed in a $thread_id, too $post = new Post($thread); // thread is a complete object, with the data I need, like thread name $post->load($post_id); // 3, inject $post into $thread, but this makes less sense to me, since I'm looking at a post page, not a thread page $post = new Post(); $post->load($post_id); $thread = new Thread($post); $thread->load(); // would load based on the $post->get('post_id') and combine. Now I have all the data I want, but it's non-intuitive to be heirarchially Thread->Post instead of Post-with-thread-info // Or, I could inject $post into $thread, but if I'm on a post page, // having an object with a top level of Thread instead of // Post-which-contains-thread-info, makes less sense to me. // to go with example 1 class post { public function __construct(&$thread) { $this->thread=$thread; } public function load($id) { // ... here I would load all the post data based on $id // now include the thread data $this->thread->load($this->get('thread_id')); return $this; } } // I don't want to do $thread = new Thread; $post = new Post; $post->load($post_id); $thread->load($post->get('post_id')); Or, I could create a new object and inject both $post and $thread into it, but then I have object with an increasing number of dependencies.

    Read the article

< Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >