Castle Interceptors With Fluent Interface - c#

I'm trying to get an interceptor I've written to work, but for some reason it doesn't seem to be instantiating the interceptor when I request my components. I'm doing something like this (forgive me if this doesn't quite compile, but you should get the idea):
container.Register(
Component.For<MyInterceptor>().LifeStyle.Transient,
AllTypes.Pick().FromAssembly(...).If(t => typeof(IView).IsAssignableFrom(t)).
Configure(c => c.LifeStyle.Is(LifestyleType.Transient).Named(...).
Interceptors(new InterceptorReference(typeof(MyInterceptor)).
WithService.FromInterface(typeof(IView)));
I've put breakpoints in the constructor for the Interceptor and it doesn't seem to be instantiating it at all.
In the past I've registered my interceptors using the XML configuration, but I'm keen to use the fluent interface.
Any help would be greatly appreciated!

I think you're misusing WithService.FromInterface. The docs say:
Uses implements to lookup the sub
interface. For example: if you have
IService and IProductService :
ISomeInterface, IService,
ISomeOtherInterface. When you call
FromInterface(typeof(IService)) then
IProductService will be used. Useful
when you want to register all your
services and but not want to specify
all of them.
You're also missing the InterceptorGroup Anywhere.
Here's a working sample, I changed it as little as possible from your sample to make it work:
[TestFixture]
public class PPTests {
public interface IFoo {
void Do();
}
public class Foo : IFoo {
public void Do() {}
}
public class MyInterceptor : IInterceptor {
public void Intercept(IInvocation invocation) {
Console.WriteLine("intercepted");
}
}
[Test]
public void Interceptor() {
var container = new WindsorContainer();
container.Register(
Component.For<MyInterceptor>().LifeStyle.Transient,
AllTypes.Pick()
.From(typeof (Foo))
.If(t => typeof (IFoo).IsAssignableFrom(t))
.Configure(c => c.LifeStyle.Is(LifestyleType.Transient)
.Interceptors(new InterceptorReference(typeof (MyInterceptor))).Anywhere)
.WithService.Select(new[] {typeof(IFoo)}));
container.Resolve<IFoo>().Do();
}
}

Related

NInject: Bind Multiple Services to Single Interface

I have interface IFoo with 2 implementations Foo1 and Foo2.
public interface IFoo
{
void Process();
}
public class Foo1 : IFoo
{
public void Process()
{
}
}
public class Foo2 : IFoo
{
public void Process()
{
}
}
I'm registering them as shown below.
kernel.Bind(x => x
.FromAssemblyContaining<IFoo>()
.SelectAllClasses().InheritedFrom<IFoo>()
.BindAllInterfaces()
.Configure(b => b.InRequestScope()));
I'm trying to get all IFoo services like this
public class TestController: ApiController
{
public TestController(IFoo[] fooServices)
{
}
}
But services list fooServices is empty. I want to get all my 2 services instead.
Please help!
Issue is resolved.
The problem was the fact, that plugin libraries are loaded via custom assembly resolver AFTER registering of services. So we exposed Kernel as static property and performed registering of its services after it was loaded.
Next issue was that 'binding' could not register 2 plugins with 1 interface.
It was resolved by traversing through each plugin types and getting their interfaces and registering as follows:
foreach (var interfaceType in pluginServiceType.GetInterfaces())
kernel.bind(interfaceType).to(pluginServiceType)

How can I dynamically register generic classes with a name with Unity?

I have an assembly with a lot of classes (300+) with a BaseClass and I want register a generic class with a interface.
With unity you have to register by {Name} if you want to resolve an array of objects of the interface.
I want an array of objects in the MainViewModel automatically.
Is there a way to automate this with reflection?
Any suggestions?
Example (pseudo):
public class BaseClass
{
public void doFoo();
}
public ClassNumber001 : BaseClass
{
}
public ClassNumber002 : BaseClass
{
}
public interface ISuperman
{
}
public class Superman : ISuperman where T : BaseClass
{
}
public MainViewModel(IEnumerable<ISuperman> lotsofSuperman)
{
}
Working example by hand:
container.RegisterType<ISuperman, Superman <ClassNumber001>>("ClassNumber001");
container.RegisterType<ISuperman, Superman <ClassNumber002>>("ClassNumber002");
container.RegisterType<IEnumerable<ISuperman>, ISuperman[]>();
This is something that comes to my mind that might work for you...
You can register the type as follows, and should work for the open generic.
container.RegisterType(typeof(ISuperman<>), typeof(Superman<>), ... );
Registering generic parameters and types
Hope this helps!
Yes, you'll need to use reflection to easily create all of the mappings that you want. Since you are using Unity 3 you can take advantage of Registration by Convention to provide help (with the heavier lifting) in registering the classes.
I've taken your pseudo code and translated it into real code:
public abstract class BaseClass
{
public abstract void DoFoo();
}
public class ClassNumber001 : BaseClass
{
public override void DoFoo()
{
Console.WriteLine("001 Foo");
}
}
public class ClassNumber002 : BaseClass
{
public override void DoFoo()
{
Console.WriteLine("002 Foo");
}
}
public interface ISuperman
{
void Do();
}
public class Superman<T> : ISuperman where T : BaseClass
{
private T baseClass;
public Superman(T baseClass)
{
this.baseClass = baseClass;
}
public void Do()
{
this.baseClass.DoFoo();
}
}
public class MainViewModel
{
public MainViewModel(IEnumerable<ISuperman> lotsofSuperman)
{
foreach(ISuperman superman in lotsofSuperman)
{
superman.Do();
}
}
}
Then use registration by convention to register all the generics:
IUnityContainer container = new UnityContainer();
container.RegisterTypes(
AllClasses.FromAssembliesInBasePath().Where(t => typeof(BaseClass).IsAssignableFrom(t))
.Select(t => typeof(Superman<>).MakeGenericType(t)),
t => new Type[] { typeof(ISuperman) },
t => t.GetGenericArguments().First().Name,
WithLifetime.Transient);
container.RegisterType<IEnumerable<ISuperman>, ISuperman[]>();
container.Resolve<MainViewModel>();
In the above code we get all classes that inherit from BaseClass and then construct a type Superman<> and map that to ISuperman using the name of the BaseClass. The RegisterTypes call will be equivalent to calling RegisterType for every BaseClass:
container.RegisterType<ISuperman, Superman<ClassNumber001>("ClassNumber001");
container.RegisterType<ISuperman, Superman<ClassNumber002>("ClassNumber002");
Then when MainViewModel is resolved it iterates over all ISuperman instances and calls a method which prints out:
001 Foo
002 Foo
showing that we injected 2 ISuperman instances: Superman<ClassNumber001> and Superman<ClassNumber002>.
If you need specific registrations for the BaseClasses (e.g. non-default lifetime manager) then you can use registration by convention to register those too).
There are some of the ways this can be done. One is by using XML where the type is defined lets say MyClass and IMyClass and during runtime it resolves based on the assemblies available. But a better approach in my opinion would be to create a project to which you can delegate the responsibility of loading up the dependencies.
Lets say you create a class like so:
public class MyClass : IMyClass
{
private readonly IUnityContainer _container;
#ctor
// initialie the container through the constructor
public void DoWork<Interface, Class>() where Class: Interface
{
_container.RegisterType<Interface, Class>(
//TODO: You can setup the container lifecycle which can be transient
// or singleton or custom based on your project requirement
)
}
}
Now whoever needs to register itself can call this interface IMyClass to get itself registered in the container and dependency can be injected to whichever class needs to perform that task.

Injecting interfaces that have generics into Nancy Bootstrapper

I'm experiencing some strange behavior with a test of mine. Here is the test code:
protected IAuditingService<BillingAudit> FakeBiometricsService;
protected Browser Browser;
[TestInitialize]
public void Initialize()
{
FakeBiometricsService = A.Fake<IAuditingService<BillingAudit>>();
A.CallTo(() => FakeBiometricsService.UpdateAudit(A<BiometricAudit[]>.Ignored)).DoesNothing();
Browser = new Browser(c => c.Module<Biometrics>().Dependency(FakeBiometricsService));
}
[TestMethod]
public void calling_endpoint_with_correct_data__calls_biometrics_service_to_save_data()
{
var response = Browser.Post("/Audits/Biometrics", with =>
{
with.HttpRequest();
with.Header("accept", "application/xml");
with.Body(JsonConvert.SerializeObject(new
{
data = new[]
{
new
{
SomeProperty = SomeValue
}
}
}));
});
response.StatusCode.Should().Be(HttpStatusCode.OK);
A.CallTo(() => FakeBiometricsService.UpdateAudit(A<BiometricAudit[]>.Ignored)).MustHaveHappened();
So what I'm trying to do here is satisfy a constraint with my A.Fake<IAuditingService<BillingAudit>>()
Here's what that my modules look like. Every module extends this base class:
public abstract class AuditModuleBase<TModel, TService> : NancyModule where TModel : BillingAudit, new() where TService : IAuditingService<TModel>, new()
{
private readonly IAuditingService<TModel> _auditingService;
protected AuditModuleBase(string endpoint, TService auditingService)
: base("/Audits/" + endpoint)
{
_auditingService = auditingService;
Post["/"] = x =>
{
var data = Request.Body.FromJson<JObject>();
return SaveLocationUpdates(data["data"].Children().Select(y => (TModel)new TModel().Parse(y)).ToArray());
};
}
private Response SaveLocationUpdates(TModel[] update)
{
_auditingService.UpdateAudit(update);
return new Response();
}
}
So, my biometrics module looks like this:
public class Biometrics : AuditModuleBase<BiometricAudit, BiometricsAuditingService>
{
public Biometrics(BiometricsAuditingService service) : base("Biometrics", service) { }
}
Sorry for the code dump. The idea is that every module extends a base class that expects a T of type BillingAudit, and an IAuditingService. However, when I pass this fake into the dependency satisfier in the Browser object, Nancy looks up the actual implementation of IAuditingService> and passes that in, which is not the desired behaviour! Is there a problem with satisfying dependencies with FakeItEasy fakes? Or interfaces with generics? Or is it something really obvious I'm overlooking?
edit: Oh, I'd also like to mention that BiometricAudit extends BillingAudit. So it's an interface with a generic of an abstract class. I've tried faking an IAuditingService and an IAuditingService, but neither seems to satisfy Nancy.
Ah, it was less exciting than I thought. Sorry! I was just being silly.
I was trying to satisfy a dependency of type BiometricsAuditingService, which is a concrete implementation of IAuditingService. Once I changed that to be an interface, everything injected properly.

C# Interfaces implementation

I don't know how manage properly the interfaces in C#. My goal is to have an abstract class for my Business Layer Services that have some common methods (like Save(), Dispose()), that call different DAL repository methods. I wish to avoid to repeat in all my services something like:
public Save()
{
repository.Save();
}
I have a scenario similar to that:
Interface
namespace Common
{
public interface IRepository
{
void Save;
void Dispose;
}
}
DAL
namespace DAL
{
public Repository : IRepository
{
public void Save() {};
public void Dispose() {};
public void Add() {}
}
}
BL
namespace BL
{
public abstrac BaseService
{
protected IRepository repository;
protected BaseService(IRepository repo)
{
repository = repo;
}
public Save()
{
repository.Save();
}
}
//...
//Tentative 1
public Service : BaseService
{
private Repository rep;
public Service()
: base(new DAL.Repository())
{
rep = base.repository; // ERROR: cannot convert IRepository to Repository
}
}
}
I tried also this:
//Tentative 2
public Service : BaseService
{
private IRepository rep;
public Service()
: base(new DAL.Repository())
{
rep = base.repository; // OK
}
public void Add()
{
rep.Add() // ERROR: IRepository doesn't contain a definition for 'Add'
}
}
I know I could define in the interface all the methods I want to use, but I'll will have to manage a lot of problems with generic types and, as you should have understand from my question, I'm quite new in C# and I wish to avoid complexity is is possible, utill I'll be more expert at least :)
Firstly I think you're having a name clash with you member
IRepository rep.
Try using
DAL.IRepository rep
The reason that you're getting an error is that you've defined "Add" as something unique to "Repository". Your member variable is an "IRepository" allowing you to put anything that implements "IRepository" onto it.
Just because you CAN put a Repository into it, doesn't mean that everything on it is going to be a repository. (Think of it look good 'ol fingers and thumbs, all thumbs are fingers, but not all fingers are thumbs)
If you NEED to call add on any repository, then add it to the interface. Else, you need to decide whether or not that member should be IRepository or Repository.
Alternatively, you COULD use
Repository myRep = rep as Repository;
if(rep!=null)
{
myRep.Add();
...
profit();
}
public Service()
: base(new DAL.Repository())
{
rep = (Repository)base.repository;
}
This way u will get the Add() service which is not a part of IRepository but a newer implementation in the extended class.
Seeing as your main problem is the lack of accessibility to the Add method, and seeing as this is a relative common method anyway, I would firstly recommend adding it to your IRepository, so it looks like this:
public interface IRepository
{
void Add();
void Save();
void Dispose();
}
You would then implement your appropriate repositories whilst inheriting from IRepository. Now, understandably you may want to be able to access custom methods on a Repository. In order to resolve this what you could do is have your BaseService accept a generic repository:
public BaseService<T> where T : IRepository
{
protected T repository { get; set; }
protected BaseService(T repo)
{
repository = repo;
}
}
Then a service would look like this
public UserService : BaseService<UserRepository>
{
public UserService() : base(new DAL.UserRepository())
{
// base.Repository is now a UserRepository.
}
}
With this implementation your UserService will be able to access all of the methods that UserRepository exposes, as it's strongly typed with the generic. Hope this helps.

NInject Extension Factory

After reading the new documentation on NInject v3 and how to use the Factory Extension, apparently I still don't get it fully since my code throws exceptions all over the place...
I get this Exception, i could paste the whole thing if people would like that but i'll try and keep it short for now.
Error activating IDeployEntityContainer No matching bindings are available,
and the type is not self-bindable.
Here is my code...
The Ninject Bind Module class
class MyNinjectModule : NinjectModule {
public override void Load() {
...
Bind<IDeployEntityFactory>().ToFactory();
Bind<IDeployEntityContainer>().To<DeployEntityContainer>();
...
}
}
The class which uses the factory
class DeployController : IDeployController {
private readonly IDeployEntityFactory _entityFactory;
public DeployController(..., IDeployEntityFactory entityFactory) {
...
}
public void Execute() {
...
//I get the Exception on this line...
_entityFactory.GetDeployEntity<IDeployEntityContainer>();
...
}
}
Factory Interface
public interface IDeployEntityFactory
{
T GetDeployEntity<T>();
}
The Factory Implementation
public class DeployEntityFactory : IDeployEntityFactory
{
private readonly IResolutionRoot _resolutionRoot;
public DeployEntityFactory(IResolutionRoot resolutionRoot)
{
_resolutionRoot = resolutionRoot;
}
public T GetDeployEntity<T>()
{
return _resolutionRoot.Get<T>();
}
}
Behind the scenes Ninject will create a proxy that implements the
specified factory interface and intercept all methods so that the
proxy behaves like...
I understand that I don't have to actually create the implementation my self if i don't need to do something special/custom in the creation of objects inside the factory.
Source: http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/
EDIT1:
Just to make sure i leave you with every bit of information you need to see the problem, i'm adding the DeployEntityContainer class/Interface
public abstract class DeployEntityBase : IDeployEntity
{
...
protected readonly IDeployEntityFactory _entityFactory;
protected DeployEntityBase(..., IDeployEntityFactory entityFactory)
{
...
_entityFactory = entityFactory;
...
}
...
}
public class DeployEntityContainer : DeployEntityBase, IDeployEntityContainer
{
...
public DeployEntityContainer(..., IDeployEntityFactory entityFactory)
: base(..., entityFactory)
{
}
}
I ended up just changing the bindings to normal bindings,
Bind<IMyFactory>().To<MyFactory>().InSingletonScope();
and it worked! My first thought was lol, but it makes sense as well.
With the ToFactory() binding it never ever used my implementation of the factory, it just generated one from the defined interface.
Now it uses my implementation. The factory is changed a bit: From newing up the kernel in the factory or injecting it in the constructor, now I inject IResolutionRoot which Get<T>(); my objects.
Here is the new code just for clarification.
class MyNinjectModule : NinjectModule {
public override void Load() {
...
Bind<IDeployEntityFactory>().To<DeployEntityfactory>().InSingletonScope();
Bind<IDeployEntityContainer>().To<DeployEntityContainer>();
...
}
}
public class DeployEntityFactory : IDeployEntityFactory
{
private readonly IResolutionRoot _resolutionRoot;
...
public DeployEntityFactory(..., IResolutionRoot resolutionRoot)
{
...
_resolutionRoot = resolutionRoot;
}
public T GetDeployEntity<T>()
{
return _resolutionRoot.Get<T>();
}
}
If this is not the right way to do it, I hope somebody can shed light on it and notify me with the right way... I imagine #remogloor would know such a thing. :)

Categories