Search Results

Search found 581 results on 24 pages for 'ioc'.

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

  • Problem Registering a Generic Repository with Windsor IoC

    - by Robin
    I’m fairly new to IoC and perhaps my understanding of generics and inheritance is not strong enough for what I’m trying to do. You might find this to be a mess. I have a generic Repository base class: public class Repository<TEntity> where TEntity : class, IEntity { private Table<TEntity> EntityTable; private string _connectionString; private string _userName; public string UserName { get { return _userName; } set { _userName = value; } } public Repository() {} public Repository(string connectionString) { _connectionString = connectionString; EntityTable = (new DataContext(connectionString)).GetTable<TEntity>(); } public Repository(string connectionString, string userName) { _connectionString = connectionString; _userName = userName; EntityTable = (new DataContext(connectionString)).GetTable<TEntity>(); } // Data access methods ... ... } and a SqlClientRepository that inherits Repository: public class SqlClientRepository : Repository<Client> { private Table<Client> ClientTable; private string _connectionString; private string _userName; public SqlClientRepository() {} public SqlClientRepository(string connectionString) : base(connectionString) { _connectionString = connectionString; ClientTable = (new DataContext(connectionString)).GetTable<Client>(); } public SqlClientRepository(string connectionString, string userName) : base(connectionString, userName) { _connectionString = connectionString; _userName = userName; ClientTable = (new DataContext(connectionString)).GetTable<Client>(); } // data access methods unique to Client repository ... } The Repository class provides some generics methods like Save, Delete, etc, that I want all my repository derived classes to share. The TEntity parameter is constrained to the IEntity interface: public interface IEntity { int Id { get; set; } NameValueCollection GetSaveRuleViolations(); NameValueCollection GetDeleteRuleViolations(); } This allows the Repository class to reference these methods within its Save and Delete methods. Unit tests work fine on mock SqlClientRepository instances as well as live unit tests on the real database. However, in the MVC context: public class ClientController : Controller { private SqlClientRepository _clientRepository; public ClientController(SqlClientRepository clientRepository) { this._clientRepository = clientRepository; } public ClientController() { } // ViewResult methods ... ... } ... _clientRepository is always null. I’m using Windor Castle as an IoC container. Here is the configuration: <component id="ClientRepository" service="DomainModel.Concrete.Repository`1[[DomainModel.Entities.Client, DomainModel]], DomainModel" type="DomainModel.Concrete.SqlClientRepository, DomainModel" lifestyle="PerWebRequest"> <parameters> <connectionString>#{myConnStr}</connectionString> </parameters> </component> I’ve tried many variations in the Windsor configuration file. I suspect it’s more of a design flaw in the above code. As I'm looking over my code, it occurs to me that when registering components with an IoC container, perhaps service must always be an interface. Could this be it? Does anybody have a suggestion? Thanks in advance.

    Read the article

  • Using IOC in a remoting scenario

    - by Christoph
    I'm struggling with getting IOC to work in a remoting scenario. I have my application server set up to publish Services (SingleCall) which are configured via XML. This works just like this as we all know: RemotingConfiguration.Configure(ConfigFile, true); lets say my service looks like that (pseudocode) public class TourService : ITourService { IRepository _repository; public TourService() { _repository = new SqlServerRepository(); } } But what I rather would like to have sure looks like this: public class TourService : ITourService { IRepository _repository; public TourService(IRepository repository) { _repository = repository; } } On the client side we do something like that (pseudocode again): (ITourService)Activator.GetObject(ITourService, tcp://server/uri); This prompts the server to create a new instance of my TourService class... However this doesn't seem to work out well because the .NET Remoting Infrastructure want's to know the type it should publish but I would rather like to point it to the way how it could retrieve the object it should publish. In other words, route it through the IOC process pipe of - let's say windsor castle - for example. Currently I'm a bit lost on that task...

    Read the article

  • The IOC "child" container / Service Locator

    - by Mystagogue
    DISCLAIMER: I know there is debate between DI and service locator patterns. I have a question that is intended to avoid the debate. This question is for the service locator fans, who happen to think like Fowler "DI...is hard to understand...on the whole I prefer to avoid it unless I need it." For the purposes of my question, I must avoid DI (reasons intentionally not given), so I'm not trying to spark a debate unrelated to my question. QUESTION: The only issue I might see with keeping my IOC container in a singleton (remember my disclaimer above), is with the use of child containers. Presumably the child containers would not themselves be singletons. At first I thought that poses a real problem. But as I thought about it, I began to think that is precisely the behavior I want (the child containers are not singletons, and can be Disposed() at will). Then my thoughts went further into a philosophical realm. Because I'm a service locator fan, I'm wondering just how necessary the notion of a child container is in the first place. In a small set of cases where I've seen the usefulness, it has either been to satisfy DI (which I'm mostly avoiding anyway), or the issue was solvable without recourse to the IOC container. My thoughts were partly inspired by the IServiceLocator interface which doesn't even bother to list a "GetChildContainer" method. So my question is just that: if you are a service locator fan, have you found that child containers are usually moot? Otherwise, when have they been essential? extra credit: If there are other philosophical issues with service locator in a singleton (aside from those posed by DI advocates), what are they?

    Read the article

  • IOC Container Handling State Params in Non-Default Constructor

    - by Mystagogue
    For the purpose of this discussion, there are two kinds of parameters an object constructor might take: state dependency or service dependency. Supplying a service dependency with an IOC container is easy: DI takes over. But in contrast, state dependencies are usually only known to the client. That is, the object requestor. It turns out that having a client supply the state params through an IOC Container is quite painful. I will show several different ways to do this, all of which have big problems, and ask the community if there is another option I'm missing. Let's begin: Before I added an IOC container to my project code, I started with a class like this: class Foobar { //parameters are state dependencies, not service dependencies public Foobar(string alpha, int omega){...}; //...other stuff } I decide to add a Logger service depdendency to the Foobar class, which perhaps I'll provide through DI: class Foobar { public Foobar(string alpha, int omega, ILogger log){...}; //...other stuff } But then I'm also told I need to make class Foobar itself "swappable." That is, I'm required to service-locate a Foobar instance. I add a new interface into the mix: class Foobar : IFoobar { public Foobar(string alpha, int omega, ILogger log){...}; //...other stuff } When I make the service locator call, it will DI the ILogger service dependency for me. Unfortunately the same is not true of the state dependencies Alpha and Omega. Some containers offer a syntax to address this: //Unity 2.0 pseudo-ish code: myContainer.Resolve<IFoobar>( new parameterOverride[] { {"alpha", "one"}, {"omega",2} } ); I like the feature, but I don't like that it is untyped and not evident to the developer what parameters must be passed (via intellisense, etc). So I look at another solution: //This is a "boiler plate" heavy approach! class Foobar : IFoobar { public Foobar (string alpha, int omega){...}; //...stuff } class FoobarFactory : IFoobarFactory { public IFoobar IFoobarFactory.Create(string alpha, int omega){ return new Foobar(alpha, omega); } } //fetch it... myContainer.Resolve<IFoobarFactory>().Create("one", 2); The above solves the type-safety and intellisense problem, but it (1) forced class Foobar to fetch an ILogger through a service locator rather than DI and (2) it requires me to make a bunch of boiler-plate (XXXFactory, IXXXFactory) for all varieties of Foobar implementations I might use. Should I decide to go with a pure service locator approach, it may not be a problem. But I still can't stand all the boiler-plate needed to make this work. So then I try this: //code named "concrete creator" class Foobar : IFoobar { public Foobar(string alpha, int omega, ILogger log){...}; static IFoobar Create(string alpha, int omega){ //unity 2.0 pseudo-ish code. Assume a common //service locator, or singleton holds the container... return Container.Resolve<IFoobar>( new parameterOverride[] {{"alpha", alpha},{"omega", omega} } ); } //Get my instance: Foobar.Create("alpha",2); I actually don't mind that I'm using the concrete "Foobar" class to create an IFoobar. It represents a base concept that I don't expect to change in my code. I also don't mind the lack of type-safety in the static "Create", because it is now encapsulated. My intellisense is working too! Any concrete instance made this way will ignore the supplied state params if they don't apply (a Unity 2.0 behavior). Perhaps a different concrete implementation "FooFoobar" might have a formal arg name mismatch, but I'm still pretty happy with it. But the big problem with this approach is that it only works effectively with Unity 2.0 (a mismatched parameter in Structure Map will throw an exception). So it is good only if I stay with Unity. The problem is, I'm beginning to like Structure Map a lot more. So now I go onto yet another option: class Foobar : IFoobar, IFoobarInit { public Foobar(ILogger log){...}; public IFoobar IFoobarInit.Initialize(string alpha, int omega){ this.alpha = alpha; this.omega = omega; return this; } } //now create it... IFoobar foo = myContainer.resolve<IFoobarInit>().Initialize("one", 2) Now with this I've got a somewhat nice compromise with the other approaches: (1) My arguments are type-safe / intellisense aware (2) I have a choice of fetching the ILogger via DI (shown above) or service locator, (3) there is no need to make one or more seperate concrete FoobarFactory classes (contrast with the verbose "boiler-plate" example code earlier), and (4) it reasonably upholds the principle "make interfaces easy to use correctly, and hard to use incorrectly." At least it arguably is no worse than the alternatives previously discussed. One acceptance barrier yet remains: I also want to apply "design by contract." Every sample I presented was intentionally favoring constructor injection (for state dependencies) because I want to preserve "invariant" support as most commonly practiced. Namely, the invariant is established when the constructor completes. In the sample above, the invarient is not established when object construction completes. As long as I'm doing home-grown "design by contract" I could just tell developers not to test the invariant until the Initialize(...) method is called. But more to the point, when .net 4.0 comes out I want to use its "code contract" support for design by contract. From what I read, it will not be compatible with this last approach. Curses! Of course it also occurs to me that my entire philosophy is off. Perhaps I'd be told that conjuring a Foobar : IFoobar via a service locator implies that it is a service - and services only have other service dependencies, they don't have state dependencies (such as the Alpha and Omega of these examples). I'm open to listening to such philosophical matters as well, but I'd also like to know what semi-authorative reference to read that would steer me down that thought path. So now I turn it to the community. What approach should I consider that I havn't yet? Must I really believe I've exhausted my options?

    Read the article

  • What's the simplest IOC container for C#?

    - by Greg
    What's the simplest IOC container for C#? Is simple to learn and get productive with for a small app. In my case a winforms app which I want to abstract the data layer for later potential migration to a web-service for the data layer.

    Read the article

  • IoC / Dependency Injection - please explain code versus XML

    - by steve.macdonald
    I understand basically how IoC frameworks work, however one thing I don't quite get is how code-based config is supposed to work. With XML I understand how you could add a new assembly to a deployed application, then change the config in XML to include it. If the application is already deployed (i.e., compiled in some form) then how can code changes be made without recompiling? Or is that what people do, just change config in code and recompile?

    Read the article

  • NHibernate + Sql Compact + IoC - Connection Managment

    - by Michael
    When working with NHibernate and Sql Compact in a Windows Form application I am wondering what is the best practice for managing connections. With SQL CE I have read that you should keep your connection open vs closing it as one would typically do with standard SQL. If that is the case and your using a IoC, would you make your repositories lifetime be singletons so they exist forever or dispose of them after you perform a "Unit of Work". Also is there a way to determine the number of connections open to Sql CE?

    Read the article

  • IoC and DI framework for .Net applications

    - by Lijo
    Hi Can you please explain how the following three are different in their intent? 1) Policy Injection Application Block 2) Structure Map IoC Managed 3) Managed Extensibility Framework In terms of the common tasks they do, which is simpler/aligned with generics and C# 3.0 ? Thanks Lijo

    Read the article

  • What IoC Containers Support Silverlight?

    - by Matt Casto
    I'm looking for a list of IoC Containers that support Silverlight. I know that Unity and Ninject work with Silverlight, but I haven't found any information that suggests that other well known containers, like StructureMap, Castle Windsor or Autofac, support Silverlight. Has anyone used these, or other, containers or compared them with the Silverlight platform in mind?

    Read the article

  • IoC.Resolve vs Constructor Injection

    - by Omu
    I heard a lot of people saying that it is a bad practice to use IoC.Resolve(), but I never heard a good reason why (if it's all about testing than you can just mock the container, and you're done). now the advantages of using Resolve instead of Constructor Injection is that you don't need to create classes that have 5 parameters in the constructor, and whenever you are going to create a instance of that class you're not gonna need to provide it with anything

    Read the article

  • When to use an IOC container?

    - by nivlam
    I'm trying to understand when I should use a container versus manually injecting dependencies. If I have an application that uses a 1-2 interfaces and only has 1-2 concrete implementations for each interface, I would lean towards just handling that myself. If I have a small application that uses 2-3 interfaces and each interface has 2-3 concrete implementations, should I use a full-blown container? Would something something simple like this suffice? Basically I'm trying to understand when it's appropriate to manually handle these dependencies, when (or if) I should use something simple like the above, and when to use an IOC container like Ninject, Windsor, etc....

    Read the article

  • IoC container configuration

    - by nivlam
    How should the configuration for an IoC container be organized? I know that registering by code should be placed at the highest level in an application, but what if an application had hundreds of dependencies that need to be registered? Same with XML configurations. I know that you can split up the XML configurations into multiple files, but that would seem like it would become a maintenance hassle if someone had to dig through multiple XML files. Are there any best practices for organizing the registration of dependencies? From all the videos and tutorials that I've seen, the code used in the demo were simple enough to place in a single location. I have yet to come across a sample application that utilizes a large number of dependencies.

    Read the article

  • IoC from start to finish

    - by Dave
    I'm quite sure that IoC is the way to go for my application. There are a ton of articles and even questions here on SO that discuss the different containers. I've read several blogs today with partial examples. I am personally leaning towards starting with the CommonServiceLocator and Unity as two way to solve the same problem -- I just need a bunch of assemblies to get data from a database, which I assume is what needs to be injected everywhere. I've yet to find any sites that really take a problem from beginning to end, with concrete code examples. For example, I've yet to find one that discusses an IServiceLocator and how to actually register it (or do whatever is required to make it known). What are your favorite posts / articles / SO questions that can take a noob from start to finish with the implementation?

    Read the article

  • Scaling Java applications - existing cluster-aware IoC frameworks?

    - by Zoltan
    Most people use some kind of an IoC framework - Guice, Spring, you name it. Many of us need to scale their applications too, so they complicate their lifes with Terracotta, Glassfish/JBoss/insertyourfavouritehere clusters. But is it really the way to go? Are you using any of the above? Here's some ideas we currently have implemented in a yet-to-be-opensourced framework, and I'd like to see what you think of it, or maybe "it's a complete ripoff of XY!". cluster-wide object replication - give it a name, and whenever you do something (in any node) on such an object, it will get replicated - with different guarantees do transparent soft-loadbalancing - simplest scenario: restful webservice method call proxied to an other node view-only node injection: inject a proxy to a "named" object, and get your calls automatically proxied to a node Would you use something like that? Is there a current, stable, enterprise-ready implementation out there?

    Read the article

  • Adding IoC Support to my WCF service hosted in a windows service (Autofac)

    - by user137348
    I'd like to setup my WCF services to use an IoC Container. There's an article in the Autofac wiki about WCF integration, but it's showing just an integration with a service hosted in IIS. But my services are hosted in a windows service. Here I got an advice to hook up the opening event http://groups.google.com/group/autofac/browse_thread/thread/23eb7ff07d8bfa03 I've followed the advice and this is what I got so far: private void RunService<T>() { var builder = new ContainerBuilder(); builder.Register(c => new DataAccessAdapter("1")).As<IDataAccessAdapter>(); ServiceHost serviceHost = new ServiceHost(typeof(T)); serviceHost.Opening += (sender, args) => serviceHost.Description.Behaviors.Add( new AutofacDependencyInjectionServiceBehavior(builder.Build(), typeof(T), ??? )); serviceHost.Open(); } The AutofacDependencyInjectionServiceBehavior has a ctor which takes 3 parameters. The third one is of type IComponentRegistration and I have no idea where can I get it from. Any ideas ? Thanks in advance.

    Read the article

  • Lightcore IoC is returning the same instance when it should give a new one

    - by Anthony
    I have the following code using the lightcore IoC container. But it fails with "NUnit.Framework.AssertionException: Contained objects are equal" which indicates that the objects that should be transient, are not. Is this a bug in lightcore, or am I doing it wrong? [Test] public void JellybeanDispenserHasNewInstanceEachTimeWithDefault() { var builder = new ContainerBuilder(); builder.Register<IJellybeanDispenser, VanillaJellybeanDispenser>(); builder.Register<SweetVendingMachine>().ControlledBy<TransientLifecycle>(); builder.Register<SweetShop>(); builder.DefaultControlledBy<TransientLifecycle>(); IContainer container = builder.Build(); SweetShop sweetShop = container.Resolve<SweetShop>(); SweetShop sweetShop2 = container.Resolve<SweetShop>(); Assert.IsFalse(ReferenceEquals(sweetShop, sweetShop2), "Root objects are equal"); Assert.IsFalse(ReferenceEquals(sweetShop.SweetVendingMachine, sweetShop2.SweetVendingMachine), "Contained objects are equal"); Assert.IsFalse(ReferenceEquals(sweetShop.SweetVendingMachine.JellybeanDispenser, sweetShop2.SweetVendingMachine.JellybeanDispenser), "services are equal"); } PS: I would tag this question with "lightcore", but suddenly my reputation isn't good enough to make a new tag. Huh.

    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

  • IoC, Containers, and NServiceBus confusion

    - by andy
    Hey guys, here's my setup Castle Windsor is my container NServiceBus is itself using it's own container internally, Spring by default I'm implementing the PubSub config. Ok, if I have my Bus.Publish happening within my IWantToRunAtStartup class, then everything is fine. As a test for example on Run() we can start a timer and it'll go into a Service style loop. However, what if I want to abstract NServiceBus from my app, and have my app go: new CustomPulisherClass().Notify(ISomeMessage msg); In this situation, how do I implement CustomPublisherClass. My confusion is coming from the fact that NServiceBus is already running as a Service, it's already been "Started". How to I get at the correct instance of the Bus object? cheers andy

    Read the article

  • StructureMap IoC problem getting the instance in runtime

    - by user274269
    i have 2 concrete types "CategoryFilter" & "StopWordsFilter" that implements "IWordTokensFilter". Below is my setup: ForRequestedType<IWordTokensFilter>().TheDefaultIsConcreteType<CategoryFilter>() .AddInstances(x => { x.OfConcreteType<StopWordsFilter>(); } ); The problem is the run-time when structure map auto inject it on my class, bec. i have arguments with same plugin-type: public ClassA(IWordTokensFilter stopWordsFilter, IWordTokensFilter categoryFilter) i'm always getting CategoryFilter in my first argument but it should be stopWordsFilter. How can i setup this in a right way? thanks in advance

    Read the article

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