s#arp castle injection - castle-windsor

I have a soap web service in my web layer (s#arp architecture) which uses a service like this:
public ReportWebService(IReportService ReportService)
{
Check.Require(ReportService != null, "ReportService may not be null");
this.ReportService = ReportService;
}
Can someone please remind me how/where I configure the injection of the implementation for IReportService again?
Thanks.
Christian

The short answer is: Just put ReportService into yourProject.ApplicationServices and it will be injected.
The long answer is: In yourProject.Web in Global.asax you will find the method InitializeServiceLocator(). This calls the static method AddComponents on ComponentRegistrar.
ComponentRegistrar is located in yourProject.web/CastleWindsor. In there you will find
public static void AddComponentsTo(IWindsorContainer container)
{
AddGenericRepositoriesTo(container);
AddCustomRepositoriesTo(container);
AddApplicationServicesTo(container);
container.AddComponent("validator",
typeof(IValidator), typeof(Validator));
}
If you look at AddApplicationServicesTo you can see that is registers all types in yourProject.ApplicationServices (.WithService.FirstInterface()):
private static void AddApplicationServicesTo(IWindsorContainer container)
{
container.Register(
AllTypes.Pick()
.FromAssemblyNamed("NewittsStore.ApplicationServices")
.WithService.FirstInterface());
}

Here is from ComponentRegistrar.cs:
/// <summary>
/// The add application services to.
/// </summary>
/// <param name="container">
/// The container.
/// </param>
private static void AddApplicationServicesTo(IWindsorContainer container)
{
container.Register(AllTypes.Pick().FromAssemblyNamed("MyAssembly.ApplicationServices").WithService.FirstInterface());
}
and here is from the a service
private readonly IDocumentManagementService _client;
public DocumentService(IDocumentManagementService client)
{
_client = client;
}
This should help you out.

Related

private constructor and static constructor in singleton pattern

I'm a c# developer.
I have confused with private constructor and static constructor in singleton pattern.
Here is my sample code in below:
standard singleton pattern and it is thread safe:
public class SingletonTest
{
private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());
/// <summary>
/// singleton pattern
/// </summary>
private SingletonTest() { }
public static RedisCacheManager Instance
{
get { return CacheManager.Value; }
}
}
second it changed the private constructor to static constructor:
public class SingletonTest
{
private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());
/// <summary>
/// static(single object in our application)
/// </summary>
static SingletonTest() { }
public static RedisCacheManager Instance
{
get { return CacheManager.Value; }
}
}
And my question is the second code still one of the singleton pattern or just it always keep a only one object(RedisCacheManager) in our application?
Somebody help me,thanks.
So to answer you question, we need to go to basic.
Static constructors have the following properties:
A static constructor is called automatically to initialize the class before the first instance is created or any static members are
referenced.
A static constructor cannot be called directly.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for
the lifetime of the application domain in which your program is
running.
But for standard singleton pattern
It will be loaded, when we call it. So we have control over, when the singleton object will be created.
User has complete control when to call it.
Hope it answers your question.

Windsor, inject container in class

Hi have the following component registered into Castle Windsor:
public class CommandDispatcher : IServiceCommandDispatcher
{
private readonly IWindsorContainer container;
public CommandDispatcher(IWindsorContainer container)
{
this.container = container;
}
#region IServiceCommandDispatcher Members
public void Dispatch<TCommand>(TCommand command) where TCommand : IServiceCommand
{
var handler = container.Resolve<IServiceCommandHandler<TCommand>>();
handler.Handle(command);
}
#endregion
}
And the dispatcher is registered in the following way:
Component
.For<IServiceCommandDispatcher>()
.ImplementedBy<CommandDispatcher>(),
But the field container is null when I resolve an instance of the dispatcher.
What should I do in order to pass the container to the resolved children items?
Windsor solves this problem for you with the Typed Factory Facility.
In the below example I want the implementation of ICommandHandlerFactory to resolve my command handler from my windsor container.
class CommandDispatcher : IServiceCommandDispatcher
{
private readonly ICommandHandlerFactory factory;
public CommandDispatcher(ICommandHandlerFactory factory)
{
this.factory = factory;
}
public void Dispatch<T>(T command) where T : IServiceCommand
{
var handler = this.factory.Create(command);
handler.Handle(command);
this.factory.Destroy(handler);
}
}
To achieve this I only need to create the ICommandHandlerFactory Interface.
public interface ICommandHandlerFactory
{
Handles<T> Create<T>(T command) where T : IServiceCommand;
void Destroy(object handler);
}
No implementation of ICommandHandlerFactory is required as Windsor will create the implementation. Windsor uses the convention that a method that returns an object is a resolve method and a method that returns void is a release method.
To register the factory you need to include using Castle.Facilities.TypedFactory and then register your factory as follows
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<ICommandHandlerFactory>()
.AsFactory()
);
Just to reiterate you do not have to write any implementation code for your factory.
This works:
container.Register(Component.For<IWindsorContainer>().Instance(container));
It's not ideal, because you still have to call the Resolve method. There may be a better way to do this, using a factory. This looks similar to what you're trying to do:
http://kozmic.net/2010/03/11/advanced-castle-windsor-ndash-generic-typed-factories-auto-release-and-more/

Having issues with Castle Windsor and Web API RC

Ok so I have looked at many posts on how to get DI working with web API. Trying to do simple ctor injection. What I am pasting here works but that doesn't mean I am happy with it. If anyone has some advice please sound off.
It appears we don't have to take control over controller creation in WEB API, which makes me question the proper releasing of dependencies. I have things setup as scoped, you will see by looking at the code. We are forced to use IDependencyResolver which I think sucks but this is the only workaround I can find as no other hooks that I have tried with IControllerActivator seem to work.
SEE CODE.
public class WindsorWeApiResolver:WindsorWebApiDependencyScope,IDependencyResolver
{
private readonly IWindsorContainer _container;
public WindsorWeApiResolver(IWindsorContainer container) : base(container)
{
_container = container;
}
public IDependencyScope BeginScope()
{
return new WindsorWebApiDependencyScope(_container);
}
}
public class WindsorWebApiDependencyScope:IDependencyScope
{
private readonly IWindsorContainer _container;
private readonly IDisposable _scope;
public WindsorWebApiDependencyScope(IWindsorContainer container)
{
_container = container;
_scope = _container.BeginScope();
}
public void Dispose()
{
_scope.Dispose();
}
public object GetService(Type serviceType)
{
return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.ResolveAll(serviceType).Cast<object>().ToArray();
}
}
I agree that IDependencyResolver is not ideal. I tried to negate the lack of release method, without fighting MVC, by using the Typed Factory Facility for the scope. See my post here. Your controllers can take constructor args as usual.
You can find a constructor injection implementation sample:
http://nikosbaxevanis.com/2012/07/16/using-the-web-api-dependency-resolver-with-castle-windsor-scoped-lifetime/

should the NServicebus CastleWindsorBuilder register the bus into the container

I have the following code:
public class MessageEndpoint : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
private IWindsorContainer _container;
public void Init()
{
_container = new WindsorContainer();
var bus = (IBus)Configure.With()
.CastleWindsorBuilder(_container)
.MsmqTransport()
.PurgeOnStartup(true);
_container.Register(Component.For<IWindsorContainer>().Instance(_container));
_container.Install(FromAssembly.This());
}
}
elsewhere in the code i am using windsor installers i.e.:
public class StorageConfiginstaller : IWindsorInstaller
{
/// <summary>
/// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer"/>.
/// </summary>
/// <param name="container">The container.</param><param name="store">The configuration store.</param>
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For<IStoreEvents>().Instance(BuildEventStore(container.Kernel)).LifeStyle.Singleton);
container.Register(Component.For<IDetectConflicts>().ImplementedBy<ConflictDetector>());
container.Register(Component.For<IRepository>().ImplementedBy<EventStoreRepository>());
container.Register(Component.For<IConstructAggregates>().ImplementedBy<AggregateFactory>());
container.Register(Component.For<IBus>().ImplementedBy<UnicastBus>());
}
private static IStoreEvents BuildEventStore(IKernel container)
{
return Wireup.Init()
.UsingRavenPersistence("EventStore", new DocumentObjectSerializer())
.UsingAsynchronousDispatcher()
.PublishTo(new DelegateMessagePublisher(c => DispatchCommit(container, c)))
.Build();
}
private static void DispatchCommit(IKernel container, Commit commit)
{
var publisher = container.Resolve<IBus>();
publisher.Publish(commit.Events.Select(e => (IMessage)e.Body).ToArray());
}
}
problem is - the bus isn't registered in the container? How do i get it so the bus is registered?
*******update********
this doesn't work?!
_container = new WindsorContainer();
var c = Configure.With()
.CastleWindsorBuilder(_container)
.MsmqTransport()
.PurgeOnStartup(true);
var bus = _container.Resolve<IBus>();
I've checked with the Pub/Sub sample where Subscriber2 is already set up to use Windsor as its container, added a constructor injected IBus property, and everything works as expected (on version 2.5).
Consider not passing in the _container and just letting NServiceBus set that up for you.

Windsor: How can I make windsor dispose a transient component when not tracking component lifecycle?

We are using the NoTrackingReleasePolicy on the Windsor container due to the memory leaks that occur when we do not Release our components after usage. Now consider the following problem.
Some disposable component:
public class DisposableComponent : IDisposable
{
private bool _disposed;
public bool Disposed
{
get { return _disposed; }
}
public void Dispose()
{
_disposed = true;
GC.SuppressFinalize(this);
}
}
Some class using the disposable component:
public class ClassWithReferenceToDisposableService
{
private DisposableComponent _disposableComponent;
public ClassWithReferenceToDisposableService(DisposableComponent disposableComponent)
{
_disposableComponent = disposableComponent;
}
}
And finaly a test which configures these components as transient and resolve/release them:
[Test]
public void ReleaseComponent_ServiceWithReferenceToTransientDisposable_TransientComponentDisposed()
{
// arrange
var windsorContainer = new WindsorContainer();
windsorContainer.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();
windsorContainer.Register(Component.For<ClassWithReferenceToDisposableService>().LifeStyle.Transient);
windsorContainer.Register(Component.For<DisposableComponent>().LifeStyle.Transient);
ClassWithReferenceToDisposableService service =
windsorContainer.Resolve<ClassWithReferenceToDisposableService>();
// act
windsorContainer.Release(service);
}
Now, if I remove the NoTrackingReleasePolicy, Windsor will dispose the transient service as expected, but I can not do this (period). Now, what I want to achieve is that Windsor disposes the transient components (anywhere in the resolve graph) when I invoke ReleaseCompnent. Is there any way to achieve this without changing the NoTrackingReleasePolicy?
No, you can't have your cake and eat it too.
You can implement your own custom policy that is kind of like NoTrackingReleasePolicy but will track some components...