w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Castle windsor: Register generics with more than one items
It fails to compile because you specific generic types with one single parameter, but you defined types with two parameters. So you should use IGenericRepository<,> and GenericRepository<,> instead of IGenericRepository<> and GenericRepository<>.

Categories : C#

Castle Windsor: How to register by convention with delegate method?
I think you can use something like this: container.Register( Classes.FromThisAssembly().BasedOn<ICommandLineOptions>().Configure(c => c.UsingFactoryMethod((kernel,context) => Program.ParseOptions(new BasicOptions()))); If you don't need the kernel or context you can simply use _ as you did above. Kind regards, Marwijn. === Edit === Use the context: container.Register( Classes.FromThisAssembly().BasedOn<ICommandLineOptions>().Configure( c => c.UsingFactoryMethod((kernel, context) => Program.ParseOptions(Activator.CreateInstance(context.RequestedType)) ) )); Alternatively if the parse function does not create a new object but just fills in properties you could do: container.Register(

Categories : C#

ASP.NET MVC Castle Windsor and DI
The problem is that you haven't registered the IController-dependency. I suppose you're thinking that you did that with the following line: container.Register(Classes.FromAssemblyContaining<HomeController>().BasedOn<IController>().LifestylePerWebRequest()); This might seem like you're doing that, but what you're actually doing is registering all the classes that implement this interface. So, when you ask the container for a HomeController, it will know how to resolve that, however, if you ask it for an IController, it won't know whether to create a HomeController or whatever other controller. What you probably want is the current active controller. In order to do this, you would probably have to inherit from the CustomControllerFactory and save the created controller in the

Categories : Asp Net Mvc

Can Castle Windsor be used to implement IDependencyResolver in ASP.NET MVC 4?
There is no difference between MVC3 and MVC4 in regards to IDependencyResolver, other than the fact there is a separate resolver for WebAPI. In my opinion, Mike Hadlow is a bit too caustic on this subject, and many other people have jumped on the bandwagon without truly considering why. Yes, it's true that Castle Windsor has a specific object lifestyle (ie lifetime management object) called Pooled that often requires you to call Release on it. And when using this lifestyle, you should probably not use IDependencyResolver because it does not provide access to this Release method (although there are ways around that too). However, I feel it's generally bad to use this lifestyle in a web application, and you should instead use the PerWebRequest lifestyle, which will automatically release

Categories : Asp Net Mvc

Getting Castle Windsor DI & FluentNhibernate Sample to Run
there was a BootController class. so going to the project settings and making the website startup hitting the url localhost/boot got the thing to load up all this Windsor, FluentNHibernate & Automapper. That created the tables in the db which allowed the app to run.

Categories : Asp Net Mvc

How to use Windsor Castle Logging Facitlity for .NET 3.5?
Castle.LoggingFacility actually supports .NET 3.5: just look at the package structure. It depends on Castle Windsor 3.0 or greater so you can't reference it via NuGet unless you upgrade CW to that minimum version. BTW the package contains just two classes and an enum so I think it is quite easy to just download the source code and recompile it.

Categories : Dotnet

Resolving generics in Windsor Castle
I'm a little bit confused about your sample... but generally speaking if you registered a component For(typeof(IControllerBase<IViewBase>)) you have to resolve it using same type. instead of var hcon = container.Resolve<ControllerBase<IViewBase>>(new { view = plug}); try var hcon = container.Resolve<IControllerBase<IViewBase>>(new { view = plug}); I'm not sure why you are registering the component using as implementation a generic type instead of the real one... that's what I might use instead container.Register (Component.For(typeof(IControllerBase<IViewBase>)).ImplementedBy(typeof(HardwareConnectionsController)).LifeStyle.Transient);

Categories : C#

Resolving empty collections with Castle Windsor
It seems to work, if I declare an empty list as a parameter to the constructor: <component id="MyClass" type="MyClass, WindsorSample"> <parameters> <myCollection> <list> </list> </myCollection> </parameters> </component> But this is not a very clean way of doing it. Also, it forces you to have a constructor which takes the collection as an argument. If anyone finds a better way to accomplish this, post it and I'll mark it as accepted.

Categories : C#

SharePoint 2010 hosted wcf and castle windsor
The error message that you are getting is that the metadata of the service is not published. To do this you need 2 things: A mex endpoint for your service: <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> And service meta data turned on in service behavior: <serviceMetadata httpGetEnabled="True" />

Categories : Wcf

Castle Windsor - Resolving duplex wcf service
After few hours of struggling, I found a work around for this problem. I think this could a bug in Castle Windsor, while creating DuplexClientModel, endpoint cannot be created using "FromConfiguration". It fails while resolving during runtime. However samething works fine with "DefaultClientModel". My workaround was to read the config file and get the address, binding and contract details and use them to create Endpoint in code. model = new DuplexClientModel { //Endpoint = WcfEndpoint.ForContract(serviceInterface).FromConfiguration(endpointName) //FromConfiguration method is failing for some reason,could be b.u.g in castle, //so had to do this workaround by reading the web.config file and creati

Categories : Wcf

Implementing the "Composite pattern" with Castle Windsor
it sounds like you are trying to do an event publisher / aggregator. there are a couple of implementations of these on the net, here is an artile: Event publisher code at the bottom of the article. The code is for 2.5, with a fix for 3.1+ in the comments. Castle has a powerful mechanism which will register types based on convention, Docs here. the above article makes use of this, to auto wire any type which implements the required interface. Also, a side note: If you want to inject all classes which implement a contract (interface) you will have to register the behaviour with castle windsor, Example of registering a sub resolver and more information can be found enter link description here Hope this helps

Categories : C#

Castle Windsor IoC inject Property into Constructor
container.Register(Component.For<ISession>() .UsingFactoryMethod(() => container .Resolve<ISessionManager>().CurrentSession) .LifeStyle.Transient);

Categories : C#

Castle Windsor - multiple implementation of an interface
My answer maybe not the best one, you can use naming method to resolve multi implementation: container.Register(Component.For(typeof(ILogger)) .ImplementedBy(typeof(FileLogger)) .Named("FileLoggerIoC") .LifestylePerWebRequest() , Component.For(typeof(ILogger)) .ImplementedBy(typeof(DatabaseLogger)) .Named("DatabaseLoggerIoC") .LifestylePerWebRequest()); In your calling functions, you need to resolve it by name :- var fileLog = container.Resolve("FileLoggerIoC", typeof(ILogger)); var DbLog = container.Resolve("DatabaseLoggerIoC", typeof(ILogger)); Mine method maybe not the best one as people don't like service locator to get the components, you can use this as temporary solution.

Categories : C#

Using Castle windsor to resolve WCF service usingfactorymethod
you don't have to create a custom ServiceHost to do this, though you're right this is harder than it should be. The article that eouw0o83hf references first talks about an IInstanceProvider. That's the key, but you can wire it up using and WCF ServiceBehavior as well instead of a customer ServiceHost. I'm not sure what your FactoryMethod has to do with this - it sounds like it's a general wire up issue... or I'm not understanding your problem. I'll show below how I do the wire up without the ServiceHost and hopefully that fixes your problem. First create a class that implements IInstanceProvider - mine below calls out to my ObjectResolver class with wraps Windsor. I'll leave that out for brevity. using System; using System.ServiceModel; using System.ServiceModel.Channels; using Syst

Categories : C#

How do you Inject a list of objects into a constructor in Castle Windsor
I've worked it out, if anyone has any feedback on whether this is a good/best solution I'd be very interested container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true)); container.Register( Component.For<IImageUpdater>() .ImplementedBy<ApplicationTileFrontImageUpdater>() .DependsOn(Property.ForKey<ApplicationUnits>().Eq(ApplicationUnits.Metric)) .Named("ApplicationTileFrontImageUpdaterMetric") ); container.Register( Component.For<IImageUpdater>() .ImplementedBy<ApplicationTileFrontImageUpdater>() .DependsOn(Property.ForKey<ApplicationUnits>().Eq(ApplicationUnits.Imperial))

Categories : List

Does strucutremap has interception capabitlities, why do i need another libratry like windsor castle for that?
The documentation answers this: StructureMap 2.5+ added the ability to postprocess or even intercept and replace the objects being created. While StructureMap will never include its own Aspect Oriented Programming model (the world does not need a new one), the interception techniques shown below could be used to apply runtime AOP from existing AOP tools like the Policy Injection Application Block from Microsoft. In general, interception is specified in three ways: 1) OnCreation() -- Registers an Action to run against the new object after creation 2) EnrichWith() -- Registers a Func that runs against the new object after creation and gives you the option of returning a different object than the original object 3) A custom class that implements the TypeInte

Categories : C#

Castle Windsor lifestyle depending on constructor parameters
I am not aware of a built-in solution, but you can always create your own ILifestyleManager. For the reference, you can look at the implementation of SingletonLifestyleManager. I never actually researched how to make custom lifestyles for Castle (we did one for Unity as far as I remember), but normally the idea is to decide when you want to resolve a new instance (CreateInstance in Castle code) and when to use the stored value. ConcurrentDictionary can help with storage in your case (though no idea what Castle's burden does, you might want to research this). Beware of the leaks if your objs are created dynamically — you may be interested in ConditionalWeakTable. Note: I agree with @Steven that in your case obj should normally be a parameter Create method, but just for the completenes

Categories : C#

Castle Windsor Interceptor to solve caching aspect
I usually use decorators for caching concerns. About removing / invalidating cache item I came out with a solution event based: real service exposes events for those behaviors changing the system(for ex adding or update an item), decorator service(caching strategy) registers itseself to those events to manage the cache.

Categories : C#

Castle windsor wcf facility - add clients through config file
Here's how I'm doing it: container.Register( Component.For<ISomeService>() .AsWcfClient(WcfEndpoint.FromConfiguration("*")) ); The "*" is actually a wildcard for an endpoint name. You could as well specify a named endpoint, but using the wildcard is my preferred way (it will then pick any endpoint with a matching service interface). Please note that LifeStyle.PerWcfOperation only works for server side components and cannot be used on a wcf client (well maybe it can, but I guess it won't do anything).

Categories : C#

Castle Windsor not supplying NLog component when using ASP.NET MVC filters
Filters are not created automatically through the container. You need to leverage IActionInvoker into your controller factory. Read this post Castle Windsor - Injecting IActionInvoker Implementation Issue EDIT Your custom filter needs to derive from ActionFilterAttribute instead of HandleErrorAttribute in order to have dependencies injected by the container (leveraging on the IActionInvoker implemented in your sample). If the purpose of your filter is handling errors, implements IExceptionFilter as well.

Categories : Asp Net Mvc

Can or should I conditionally bind interfaces at runtime with Castle Windsor?
It depends on whether your app architecture is fit for dependency injection. Not familiar with Castle Windsor but generally speaking, if a dependency can't be resolved at the composition root (app startup) I see nothing wrong with injecting a factory implementation that works with current http context. For example, in an ASP.NET application your composition root would be in global.asax. There you could bind some IBreadcrumbRetrieverFactory to a BreadcrumbRetrieverFactory implementation. newing up classes that aren't part of the core framework (and a few that are) is generally a sign of a missed DI opportunity (and of tight coupling). IoC containers and DI aren't a silver bullet: Depencency Injection is merely a design pattern (think constructor injection, constructors that only assign p

Categories : C#

Windsor Castle object factory "GetByName" injecting properties
Once again Typed factory is the solution.

Categories : C#

The operation cannot be completed because the DbContext has been disposed with EF5 SignalR and Windsor Castle as IoC
Looks to me like you're injecting your UoW into the Hub, but expecting to use the instance in a timer callback. The problem is that the hub instance and its dependencies will have been logically cleaned up (e.g. disposed) after it processes the last message it received, so when the timer callback fires it's finding an already disposed instance. It's better to move this kind of timer based logic out of the hub into a separate class that resolves the hub context to fire messages when it needs to. So, here's an example of what the logic to get and send a message to the hub might look like in that class: // Get a hub context for ServerHub IHubContext serverHub = GlobalHost.ConnectionManager.GetHubContext<ServerHub>(); // Send a message to all the clients serverHub.Clients.

Categories : Asp Net Web Api

Castle windsor resolve array with open generic and interface
First, I think that you should improve your design a bit. I don't know the actual context, but I believe that your intent is the following: public interface IEntity { } public class Entity1 : IEntity { } public class Entity2 : IEntity { } public abstract class Definition<TEntity> where TEntity : IEntity { } public class Entity1Definition : Definition<Entity1> { } public class Entity2Definition : Definition<Entity2> { } With this design you have the problem that the following code is not valid: Definition<IEntity> definition = new Entity1Definition(); In order for this to work you should introduce a covariant generic interface for the IEntity type. More on covariance and contravariance you can find here: Covariance and Contravariance in Generics So I

Categories : C#

Entity Framework with Castle Windsor IoC Container - Validation Error
Castle Windsor does implicit property injection by default, which means that it will try to inject every public property on the type that's being created. When an Employee has a Department property, it will try to create a Department instance and if it succeeds, it will inject it into that property. This is clearly what's happening here. You should use your IoC container only for building up object graphs of services, not entities. Don't do that.

Categories : Entity Framework

Castle Windsor Configuration: Set Order for FromAssembly.InDirectory for Decorators
My old approach for this scenario was to register declarators within web.config or dedicated xml file. Since version 3.1 you can specify a Default component for a given interface: using a naming convention strategy became pretty easy to set decorators as default component, no matter the concrete registrations. An other approach I use to ensure registration order, not just for decorators, is creating an InstallerFactory so you can easily drive installers execution order. Sorry if I do not provide any code example... But I'm in vacation right now

Categories : C#

How can I properly set up a cache on a typedfactory using the decorator pattern (Castle Windsor)?
You are registering both the cached and typedfactory as singletons (implicitly). If you register the TypeFactory as Transient it will probably (not completely sure) be disposed right after the cached factory. However since you only try to cleanup the resolved components of the factory you could also simply omit the code in Dispose as the typed factory will release all it's components when it is released.

Categories : Caching

Castle Windsor inject dependency depending on another parameter in the constructor
If I understand well, you would like Castle Windsor to guess that he have to use the given instance of Value when resolving DependentClass AND DependentParameter. With the current version of Castle, the construction of Dependencies does not use the initial argument list. So you have to wait until Castle implement this behavior (I don't even know if it will be done one day). What you could do if you're not patient enough, is to use a little trick. In fact there is a way in Castle to keep the context (and so the argument list) when resolving Dependencies, but it depends on the Dependency herself. As soon as the Dependency is Generic, the context will be conserved. For exemple in your case you could do the following change : public class DependentParameter<T> : IDependentParameter

Categories : C#

Creating a Castle Windsor Controller Factory and GetControllerInstance is never called
I can't spot any mistake at the first sight... But for sure your plumbing is redundant... Keept it simple as per windsor tutorial

Categories : C#

Castle windsor - null object with Dependecy Injection of class that inherits from a generic base class
My guess is related to inheritance... "Generic Dao" inherit from "Non generic Dao"... that might(didn't try) create fluent registration confusion... first registration might register also generic daos due to inheritance... also be careful to WithServiceAllInterfaces, usually DefaultInterfaces is enough I rather use a generic interface for all repositories. IRepository where T:Entity: try to implement the repository pattern properly, than you'll register all daos/repositories in one shot Classes.FromAssemblyNamed("COGE.Business") .BasedOn(typeof(IRepository<>)) .WithService.DefaultInterfaces().LifestyleTransient() I don't see the point in your code for generic dao... you are not leveraging generic dao/repository pattern.

Categories : C#

How do you pass an IOC target into another IOC target using Castle Windsor?
Not entirely sure what you're trying to do from this example? The only thing I can suggest is this would be something handled in the concrete type (nothing to do with Castle Windsor). So: Public Class Foo { Public Foo(IBar bar) { bar.Create(typeof(Foo)); } } Edit: What you seem to be saying is you want Foo to be constructed by Bar as a factory. In which case, coupling between a factory and the types it is responsible for creating is acceptable. You could therefore pass the factory IBar into any class that requires an instance of IFoo and call the create method directly. You can then, if you needed to, switch the factory implementation mappings of IBar to give you whatever concrete IFoo's required.

Categories : C#

Microarchitectural zeroing of a register via the register renamer: performance versus a mov?
Executive summary: You can run up to four xor ax, ax instructions per cycle as compared to the slower mov immediate, reg instructions. Details and references: Wikipedia has a nice overview of register renaming in general: http://en.wikipedia.org/wiki/Register_renaming Torbj¨orn Granlund's timings for instruction latencies and throughput for AMD and Intel x86 processors are at: http://gmplib.org/~tege/x86-timing.pdf Agner Fog nicely covers the specifics in his Micro-architecture study: 8.8 Register allocation and renaming Register renaming is controlled by the register alias table (RAT) and the reorder buffer (ROB) ... The µops from the decoders and the stack engine go to the RAT via a queue and then to the ROB-read and the reservation station. The RAT can handle 4

Categories : Assembly

GCM (Google cloud messaging) - can I register multiple devices with same register id?
No. Moreover, you should not need to. You can use user notifications to be able to send a single message from the server to all instances of your app across all the user's devices.

Categories : Android

Why does this mathematical operation work? (Getting 8-bit register from 32-bit register)
"mod 256" is the remainder after division by 256. In binary, this turns out to be the lowest 8 bits (because 256 is 2 to the 8th). This is just like "mod 2" gives you the least significant bit (0 or 1). On (in decimal, base 10), "mod 100" gives you the last two decimals ( 2013 mod 100 => 13).

Categories : Assembly

Implementing Windsor, migrating and have questions
You don't have to do anything except registering that created instance in the container: Kernel.Register(Component.For<ILinkedInService>() .Instance(LinkedInServiceHelper.LinkedInService)));

Categories : Asp Net Mvc

Windsor Component registration based on common interface
it depends on how you want to use it (inject it) here's is a possible solution container.Register( Classes .FromThisAssembly() .BasedOn<ISettings>() .WithServiceSelf() //for way 3 .WithServiceFirstInterface() //way 1 & 2 .Configure(c => c.Named(c.Implementation.Name)) //way 1 & 2 ); Way 1 - resolve directly - I do not think you will be using this one in your example you are gettings the settings directly, you can used the named parameter with the container as follows var settings = container.Resolve<ISettings>("EmailSettings"); when resolving the settings this way we used the named parameter to select the correct implementation. Way 2 - injection using the named parameter in this case we have a service as follows (again guessing a

Categories : Dotnet

Castle Interceptor not Intercepting
changed main to : container = new WindsorContainer(); container.Register( Component.For<ICalcService>().ImplementedBy<Calc>().Interceptors<MyLogger>(), Component.For<MyLogger>().LifeStyle.Transient); ICalcService c = container.Resolve<ICalcService>(); Console.WriteLine(c.Add(3, 4)); Console.ReadKey(); And you can remove the interceptor attribute. If you want to do interception with windsor then Windsor must be allowed to created the component(s).

Categories : C#

castle activerecord lazy get id
the following code should allow you to get the id (but I couldn't test it at the moment): int id = (int)((INHibernateProxy)order.Customer).HibernateLazyInitializer.Identifier; Greetings Juy Juka

Categories : Misc

implementing bouncy castle aes 256
You are using String.getBytes() on a regular basis. That's almost certain one location where you make an error. getBytes() is platform dependent, so you may get different bytes on different systems. Furthermore, not all bytes are valid character encodings. So if your key/IV consists of secure random bytes (which they should) then your decryption will fail...sometimes. The general answer is to convert characters to bytes using a well specified character-encoding (e.g. UTF-8) and bytes to characters using an encoding like base-64 or hexadecimals.

Categories : Java

How to change a target using Castle DynamicProxy
use CreateInterfaceProxyWithTargetInterface That one will allow you to change the proxy/invocation target. Also the IChangeProxyTarget is implemented by invocation type, not the proxy itself.

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.