I am new to IoC and especially Castle Windsor. I'm trying to register component for eventpublisher which look like this:
container.Register(Component.For<IEventPublisher>().ImplementedBy<EventPublisher>());
I'm sure that the container register code above is correct, but I get another error message which says:
Can't create component 'Network.Infrastructure.Event.EventPublisher' as it has dependencies to be satisfied.'Network.Infrastructure.Event.EventPublisher' is waiting for the following dependencies:- Service 'System.Collections.Generic.IEnumerable`1[[Network.Infrastructure.Event.IEventListener, Network.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' which was not registered.
I have also tried to register IEventListener, but with no luck.
ArticleService.cs
public class ArticleService : IArticleService
{
private readonly IArticleRepository _articleRpRepository;
private readonly IUnitOfWork _unitOfWork;
**Declaring the field for IEventPublisher**
private readonly IEventPublisher _eventPublisher;
public ArticleService(IArticleRepository articleRpRepository, IUnitOfWork unitOfWork, IEventPublisher eventListener)
{
_articleRpRepository = articleRpRepository;
_eventPublisher = eventListener;
_unitOfWork = unitOfWork;
}
public Article CreateArticle(Article article)
{
**Using the publish from eventpublish class**
_eventPublisher.Publish(new MyEvent { Message = "Something is done" });
article.Created = DateTime.Now;
_articleRpRepository.Add(article);
SaveChanges();
return article;
}
}
EventPublisher.cs
public class EventPublisher : IEventPublisher
{
private readonly IEnumerable<IEventListener> _listeners;
public EventPublisher(IEnumerable<IEventListener> listeners)
{
_listeners = listeners;
}
public void Publish<TPayload>(TPayload payload) where TPayload : class
{
var handlersForPayload = _listeners.OfType<IEventListener<TPayload();
foreach (var handler in handlersForPayload)
{
handler.Handle(payload);
}
}
}
IEventListener.cs
public interface IEventListener
{}
public interface IEventListener<in TPayload> : IEventListener where TPayload : class
{
void Handle(TPayload payload);
}
You need to add CollectionResolver to the container and than register your listeners.
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
More info about resolvers here:
https://github.com/castleproject/Windsor/blob/master/docs/resolvers.md