Search Results

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

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

  • NHibernate Session DI from StructureMap in components

    - by Corey Coogan
    I know this is somewhat of a dead horse, but I'm not finding a satisfactory answer. First let me say, I am NOT dealing with a web app, otherwise managing NH Session is quite simple. I have a bunch of enterprise components. Those components have their own service layer that will act on multiple repositories. For example: Claim Component Claim Processing Service Claim Repository Billing Component Billing Service Billing REpository Policy Component PolicyLockService Policy Repository Now I may have a console, or windows application that needs to coordinate an operation that involves each of the services. I want to write the services to be injected with (DI) their required repositories. The Repositories should have an ISession, or similar, injected into them so that I can have this operation performed under one ISession/ITransaction. I'm aware of the Unit Of Work pattern and the many samples out there, but none of them showed DI. I'm also leery of [ThreadStatic] because this stuff can also be used from WCF and I have found enough posts describing how to do that. I've read about Business Conversations, but need something simple that each windows/console app can easily bootstrap since we have alot of these apps and some pretty inexperienced developers. So how can I configure StructureMap to inject the same ISession into each of the dependent repositories from an application? Here's a totally contrived and totally made up example without using SM (for clarification only - please don't spend energy critisizing): ConsoleApplication Main { using(ISession session = GetSession()) using(ITransaction trans = session.BeginTransaction()) { var policyRepo = new PolicyRepo(session); var policyService = new PolicyService(policyRepo); var billingRepo = new BillingRepo(session) var billingService = new BillingService(billingRepo); var claimRepo = new ClaimsRepo(session); var claimService = new ClaimService(claimRepo, policyService, billingService); claimService.FileCLaim(); trans.Commit(); } }

    Read the article

  • Define Default constructor Structuremap in a Generic Repository

    - by Ricky
    Hello guys, I have a generic IRepository that has 2 constructors, one have none parameters, other has the datacontext as parameter. I want to define to structuremap to aways in this case use the parameterless constructor. I want a way to create a parameterless contructor, other solutions that I have seen, they create a new Datacontext and pass it to the constructor that has parameters.

    Read the article

  • Using StructureMap, how do you explicitly trigger the reinstantiation of a object with InstanceScope

    - by Mark Rogers
    I have an integration test harness where I want to teardown and then re-instantiate some of the singleton-scoped objects I've registered with StructureMap, after and before each test. This way I can simulate the actual run time environment, but not have the singleton's state being passed from one test to another. Maybe this isn't a great way to do an integration test, but I'm running out of alternative solutions (read open to any advice). So can an object with InstanceScope.Singleton, be re-instantiated? What's the best way to do re-instantiate a singleton-scoped object with StructureMap?

    Read the article

  • How to inject dependencies into a custom UserNamePasswordValidator in WCF?

    - by Dannerbo
    I'm using a UserNamePasswordValidator in WCF along with Unity for my dependency injection, but since WCF creates the instance of the UserNamePasswordValidator, I cannot inject my container into the class. So how would one go about this? The simplest solution I can think of is to create a static proxy/wrapper class around a static instance of a UnityContainer, which exposes all the same methods... This way, any class can access the container, and I don't need to inject it everywhere. So I could just do UnityContainerWrapper.Resolve() anywhere in code. So basically this solution solves 2 problems for me, I can use it in classes that I'm not creating an instance of, and I can use it anywhere without having to inject the container into a bunch of classes. The only downside I can think of is that I'm now potentially exposing my container to a bunch of classes that wouldn't of had access to the container before. Not really sure if this is even a problem though?

    Read the article

  • Did the Unity Team fix that "generics handling" bug back in 2008?

    - by rasx
    At my level of experience with Unity it might be faster to ask whether the "generics handling" bug acknowledged by ctavares back in 2008 was fixed in a public release. Here was the problem (which might be my problem today): Hi, I get an exception when using .... container.RegisterType(typeof(IDictionary<,), typeof(Dictionary<,)); The exception is... "Resolution of the dependency failed, type = \"IDictionary2\", name = \"\". Exception message is: The current build operation (build key Build Key[System.Collections.Generic.Dictionary2[System.String,System.String], null]) failed: The current build operation (build key Build Key[System.Collections.Generic.Dictionary2[System.String,System.String], null]) failed: The type Dictionary2 has multiple constructors of length 2. Unable to disambiguate. When I attempt... IDictionary myExampleDictionary = container.Resolve(); Here was the moderated response: There are no books that'll help, Unity is a little too new for publishers to have caught up yet. Unfortunately, you've run into a bug in our generics handling. This is currently fixed in our internal version, but it'll be a little while before we can get the bits out. In the meantime, as a workaround you could do something like this instead: public class WorkaroundDictionary : Dictionary { public WorkaroundDictionary() { } } container.RegisterType(typeof(IDictionary<,),typeof(WorkaroundDictionary<,)); The WorkaroundDictionary only has the default constructor so it'll inject no problem. Since the rest of your app is written in terms of IDictionary, when we get the fixed version done you can just replace the registration with the real Dictionary class, throw out the workaround, and everything will still just work. Sorry about the bug, it'll be fixed soon!

    Read the article

  • Dependency Injection mechanism

    - by abc
    The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing. what does it mean actually ?

    Read the article

  • Get instance of type inheriting from base class, implementing interface, using StructureMap

    - by Ben
    Continuing on my quest for a good plugin implementation I have been testing the StructureMap assembly scanning features. All plugins will inherit from abstract class PluginBase. This will provide access to common application services such as logging. Depending on it's function, each plugin may then implement additional interfaces, for example, IStartUpTask. I am initializing my plugins like so: Scan(x => { x.AssembliesFromPath(HttpContext.Current.Server.MapPath("~/Plugins"), assembly => assembly.GetName().Name.Contains("Extension")); x.AddAllTypesOf<PluginBase>(); }); The difficulty I am then having is how to work against the interface (not the PluginBase) in code. It's easy enough to work with PluginBase: var plugins = ObjectFactory.GetAllInstances<PluginBase>(); foreach (var plugin in plugins) { } But specific functionality (e.g. IStartUpTask.RunTask) is tied to the interface, not the base class. I appreciate this may not be specific to structuremap (perhaps more a question of reflection). Thanks, Ben

    Read the article

  • Trouble with object injection in Spring.Net

    - by Abdel Olakara
    Hi all, I have a issue with my Spring.Net configuration where its not injecting an object. I have a CommService to which an object named GeneralEmail is injected to. Here is the configuration: <!-- GeneralMail Object --> <object id="GeneralMailObject" type="CommUtil.Email.GeneralEmail, CommUtil"> <constructor-arg name="host" value="xxxxx.com"/> <constructor-arg name="port" value="25"/> <constructor-arg name="user" value="[email protected]"/> <constructor-arg name="password" value="xxxxx"/> <constructor-arg name="template" value="xxxxx"/> </object> <!-- Communication Service --> <object id="CommServiceObject" type="TApp.Code.Services.CommService, TApp"> <property name="emailService" ref="GeneralMailObject" /> </object> The communication service object is again injected to many other aspx pages & service. In one scenario, I need to call the commnucation service from an static WebMethod. I try doing: CommService cso = new CommService(); But when i try to get the emailService object, its null! why didn't the spring inject the GeneralMail object into my cso object? What am I doing wrong and how do I access the object from spring container. Thanks in advance for the suggestions and solutions. Reagrds, Abdel Olakara

    Read the article

  • How can I configure a Factory with the possible providers?

    - by Jonathas Costa
    I have three assemblies: "Framework.DataAccess", "Framework.DataAccess.NHibernateProvider" and "Company.DataAccess". Inside the assembly "Framework.DataAccess", I have my factory (with the wrong implementation of discovery): public class DaoFactory { private static readonly object locker = new object(); private static IWindsorContainer _daoContainer; protected static IWindsorContainer DaoContainer { get { if (_daoContainer == null) { lock (locker) { if (_daoContainer != null) return _daoContainer; _daoContainer = new WindsorContainer(new XmlInterpreter()); // THIS IS WRONG! THIS ASSEMBLY CANNOT KNOW ABOUT SPECIALIZATIONS! _daoContainer.Register( AllTypes.FromAssemblyNamed("Company.DataAccess") .BasedOn(typeof(IReadDao<>)).WithService.FromInterface(), AllTypes.FromAssemblyNamed("Framework.DataAccess.NHibernateProvider") .BasedOn(typeof(IReadDao<>)).WithService.Base()); } } return _daoContainer; } } public static T Create<T>() where T : IDao { return DaoContainer.Resolve<T>(); } } This assembly also defines the base interface for data access IReadDao: public interface IReadDao<T> { IEnumerable<T> GetAll(); } I want to keep this assembly generic and with no references. This is my base data access assembly. Then I have the NHibernate provider's assembly, which implements the above IReadDao using NHibernate's approach. This assembly references the "Framework.DataAccess" assembly. public class NHibernateDao<T> : IReadDao<T> { public NHibernateDao() { } public virtual IEnumerable<T> GetAll() { throw new NotImplementedException(); } } At last, I have the "Company.DataAccess" assembly, which can override the default implementation of NHibernate provider and references both previously seen assemblies. public interface IProductDao : IReadDao<Product> { Product GetByName(string name); } public class ProductDao : NHibernateDao<Product>, IProductDao { public override IEnumerable<Product> GetAll() { throw new NotImplementedException("new one!"); } public Product GetByName(string name) { throw new NotImplementedException(); } } I want to be able to write... IRead<Product> dao = DaoFactory.Create<IRead<Product>>(); ... and then get the ProductDao implementation. But I can't hold inside my base data access any reference to specific assemblies! My initial idea was to read that from a xml config file. So, my question is: How can I externally configure this factory to use a specific provider as my default implementation and my client implementation?

    Read the article

  • StructureMap and injecting IEnumerable<T>

    - by GiddyUpHorsey
    I'm new to StructureMap and have some existing code that I'm working with that uses StructureMap 2.5.4. There is a class that is constructed using StructureMap that has a constructor that takes IEnumerable<TCar> as a parameter. The registry has the following code. Scan(x => { x.TheCallingAssembly(); x.WithDefaultConventions(); x.AddAllTypesOf<ICar>(); } ); ForRequestedType<IEnumerable<ICar>>().TheDefault.Is.ConstructedBy( x => ObjectFactory.GetAllInstances<ICar>()); I'm writing a unit test and have obtained a nested container off the ObjectFactory and have injected an instance using the Inject method. One of the instances of ICar should receive the injected type in its constructor. However it wasn't working and I tracked that down to the ObjectFactory.GetAllInstances() call which doesn't use my nested container. How can I get this to work? I also read about StructureMap autowiring arrays and IEnumerable instances but I couldn't get it to work. Is there a better way to rewrite the above registry code so that an instance of IEnumerable<TCar> will be created and use the injected type from my nested container?

    Read the article

  • Injecting all registered instances of a type

    - by James L
    I can successfully perform container.ResolveAll<IMyInterface>(), and I get back an Enumerable containing every registered IMyInterface. However, I can't find a way to have these injected into the constructor of my class. I have tried using ResolvedArrayParameter(), but this gives me an empty enumerator. Am I doing something wrong, or could this be a bug in Unity?

    Read the article

  • Can't Instantiate Windsor Custom Component Activator

    - by jeffn825
    Hi, I'm getting an exception calling Resolve: KernelException: Could not instantiate custom activator Inner Exception: {"Constructor on type 'MyProj.MyAdapter`1[[MyProj.MyBusinessObject, MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found."} There's definitely a public parameterless constructor there (and I've verified this using reflection at runtime)...so I figure the problem might have to do with the fact that it's generic? I've tried getting the component model object and setting RequiresGenericArguments to true, but that hasn't gotten me anywhere. Any help would be much appreciated! Thanks.

    Read the article

  • Calling DI Container directly in method code (MVC Actions)

    - by fearofawhackplanet
    I'm playing with DI (using Unity). I've learned how to do Constructor and Property injection. I have a static container exposed through a property in my Global.asax file (MvcApplication class). I have a need for a number of different objects in my Controller. It doesn't seem right to inject these throught the constructor, partly because of the high quantity of them, and partly because they are only needed in some Actions methods. The question is, is there anything wrong with just calling my container directly from within the Action methods? public ActionResult Foo() { IBar bar = (Bar)MvcApplication.Container.Resolve(IBar); // ... Bar uses a default constructor, I'm not actually doing any // injection here, I'm just telling my conatiner to give me Bar // when I ask for IBar so I can hide the existence of the concrete // Bar from my Controller. } This seems the simplest and most efficient way of doing things, but I've never seen an example used in this way. Is there anything wrong with this? Am I missing the concept in some way?

    Read the article

  • Unity Framework constructor parameters in MVC

    - by ubersteve
    I have an ASP.NET MVC3 site that I want to be able to use different types of email service, depending on how busy the site is. Consider the following: public interface IEmailService { void SendEmail(MailMessage mailMessage); } public class LocalEmailService : IEmailService { public LocalEmailService() { // no setup required } public void SendEmail(MailMessage mailMessage) { // send email via local smtp server, write it to a text file, whatever } } public class BetterEmailService : IEmailService { public BetterEmailService (string smtpServer, string portNumber, string username, string password) { // initialize the object with the parameters } public void SendEmail(MailMessage mailMessage) { //actually send the email } } Whilst the site is in development, all of my controllers will send emails via the LocalEmailService; when the site is in production, they will use the BetterEmailService. My question is twofold: 1) How exactly do I pass the BetterEmailService constructor parameters? Is it something like this (from ~/Bootstrapper.cs): private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); container.RegisterType<IEmailService, BetterEmailService>("server name", "port", "username", "password"); return container; } 2) Is there a better way of doing that - i.e. putting those keys in the web.config or another configuration file so that the site would not need to be recompiled to switch which email service it was using? Many thanks!

    Read the article

  • Castle, sharing a transient component between a decorator and a decorated component

    - by Marius
    Consider the following example: public interface ITask { void Execute(); } public class LoggingTaskRunner : ITask { private readonly ITask _taskToDecorate; private readonly MessageBuffer _messageBuffer; public LoggingTaskRunner(ITask taskToDecorate, MessageBuffer messageBuffer) { _taskToDecorate = taskToDecorate; _messageBuffer = messageBuffer; } public void Execute() { _taskToDecorate.Execute(); Log(_messageBuffer); } private void Log(MessageBuffer messageBuffer) {} } public class TaskRunner : ITask { public TaskRunner(MessageBuffer messageBuffer) { } public void Execute() { } } public class MessageBuffer { } public class Configuration { public void Configure() { IWindsorContainer container = null; container.Register( Component.For<MessageBuffer>() .LifeStyle.Transient); container.Register( Component.For<ITask>() .ImplementedBy<LoggingTaskRunner>() .ServiceOverrides(ServiceOverride.ForKey("taskToDecorate").Eq("task.to.decorate"))); container.Register( Component.For<ITask>() .ImplementedBy<TaskRunner>() .Named("task.to.decorate")); } } How can I make Windsor instantiate the "shared" transient component so that both "Decorator" and "Decorated" gets the same instance? Edit: since the design is being critiqued I am posting something closer to what is being done in the app. Maybe someone can suggest a better solution (if sharing the transient resource between a logger and the true task is considered a bad design)

    Read the article

  • How to inject dependencies into a CustomUserNamePasswordValidator in WCF?

    - by Dannerbo
    I'm using a UserNamePasswordValidator in WCF along with Unity for my dependency injection, but since WCF creates the instance of the UserNamePasswordValidator, I cannot inject my container into the class. So how would one go about this? The simplest solution I can think of is to create a static proxy/wrapper class around a static instance of a UnityContainer, which exposes all the same methods... This way, any class can access the container, and I don't need to inject it everywhere. So I could just do UnityContainerWrapper.Resolve() anywhere in code. So basically this solution solves 2 problems for me, I can use it in classes that I'm not creating an instance of, and I can use it anywhere without having to inject the container into a bunch of classes. The only downside I can think of is that I'm now potentially exposing my container to a bunch of classes that wouldn't of had access to the container before. Not really sure if this is even a problem though?

    Read the article

  • Importing into a Exported object with MEF

    - by Nathan W
    I'm sorry if this question has already been asked 100 times, but I'm really struggling to get it to work. Say I have have three projects. Core.dll Has common interfaces Shell.exe Loads all modules in assembly folder. References Core.dll ModuleA.dll Exports Name, Version of module. References Core.dll Shell.exe has a [Export] that contains an single instance of a third party application that I need to inject into all loaded modules. So far the code that I have in Shell.exe is: static void Main(string[] args) { ThirdPartyApp map = new ThirdPartyApp(); var ad = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var dircatalog = new DirectoryCatalog("."); var a = new AggregateCatalog(dircatalog, ad); // Not to sure what to do here. } class Test { [Export(typeof(ThirdPartyApp))] public ThirdPartyApp Instance { get; set; } [Import(typeof(IModule))] public IModule Module { get; set; } } I need to create a instance of Test, and load Instance with map from the Main method then load the Module from ModuleA.dll that is in the executing directory then [Import] Instance into the loaded module. In ModuleA I have a class like this: [Export(IModule)] class Module : IModule { [Import(ThirdPartyApp)] public ThirdPartyApp Instance {get;set;} } I know I'm half way there I just don't know how to put it all together, mainly with loading up test with a instance of map from Main. Could anyone help me with this.

    Read the article

  • Multiple exports with MEF does some really heinous stuff -- why, and why is it allowed?

    - by Dave
    I have an interesting situation where I need to do something like this: [Export[typeof(ICandy1)] [Export[typeof(ICandy2)] public class Candy : ICandy2 { ... } where public interface ICandy1 { ... } public interface ICandy2 : ICandy1 { ... } I couldn't find any posts anywhere regarding using multiple [Export] attributes, so I figured, what the hell, might as well try it. At first glance, it actually seemed to work. I have a couple of methods that call into both interfaces of a Candy instance, and it was fine. However, as I started to test the app, I saw that the behavior wasn't right, and when looking at the Output window, I saw that I was getting tons of COMExceptions. I couldn't track down where they were all coming from, but they always occurred when a worker thread was sleeping. I figured that it had to be from the main thread, then, but didn't know how to debug this at all. Nothing should have been going on in the GUI, and I disabled my DispatchTimers just in case -- same thing. Even more strange than the COMExceptions was the really, really erratic behavior when stepping through code. About 30% of the time, when I single stepped, it would pop out of the method, or it would single step over two lines of code! Totally weird stuff that I am not used to seeing. The only thing that changed between working and non-working code was the introduction of MEF through my plugin loading code. So as a test, I changed my plugin assembly to only export one interface, and I hardcoded everything in the app that relied on the other (now not-implemented) interface. And now the COMExceptions are gone, and the weird debugging behavior is gone. Is this something people here have seen before? If MEF is not expected to allow a class to Export multiple interfaces, then shouldn't a CompositionException get raised when composing the parts? Can anyone explain why MEF would cause these weird problems???

    Read the article

  • Castle Windsor: Reuse resolved component in OnCreate, UsingFactoryMethod or DynamicParameters

    - by shovavnik
    I'm trying to execute an action on a resolved component before it is returned as a dependency to the application. For example, with this graph: public class Foo : IFoo { } public class Bar { IFoo _foo; IBaz _baz; public Bar(IFoo foo, IBaz baz) { _foo = foo; _baz = baz; } } When I create an instance of IFoo, I want the container to instantiate Bar and pass the already-resolved IFoo to it, along with any other dependencies it requires. So when I call: var foo = container.Resolve<IFoo>(); The container should automatically call: container.Resolve<Bar>(); // should pass foo and instantiate IBaz I've tried using OnCreate, DynamicParameters and UsingFactoryMethod, but the problem they all share is that they don't hold an explicit reference to the component: DynamicParameters is called before IFoo is instantiated. OnCreate is called after, but the delegate doesn't pass the instance. UsingFactoryMethod doesn't help because I need to register these components with TService and TComponent. Ideally, I'd like a registration to look something like this: container.Register<IFoo, Foo>((kernel, foo) => kernel.Resolve<Bar>(new { foo })); Note that IFoo and Bar are registered with the transient life style, which means that the already-resolved instance has to be passed to Bar - it can't be "re-resolved". Is this possible? Am I missing something?

    Read the article

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