I have created one Parent library where in, I have a abstract class,and I have another child library where I have inherited the parent library, now I'm consuming this child library in web API controller, so, I would be consuming this in service layer,however, I'm not sure how to use it correctly, secondly I have all, the methods inside this library as protected, please guide how to do dependency injection for abstract class or do I need to create another interface or something for DI?
Code:
// Parent library
public abstract class Page
{
protected abstract void ImplementAbstractMethod();
}
// Child library
public class ImplementPage : Page
{
protected override void ImplementAbstractMethod()
{
// Implementation...
}
}
// Web API
public class ServiceController
{
public ServiceController( ????) // How to do dependency injection, should I use abstract class, if yes then how to consume protected method, or, do I need to make it public?
{
}
}
// Or In business layer
public class Service
{
public Service( ????) // How to do dependency injection, should I use abstract class, if yes then how to consume protected method, or, should I inherit the child library??
{
}
}
Related
Its easy enough using NInject to establish dependency injection using interfaces.
So for example say I have a class like
public class WindowManagerService : IWindowManager
{
public WindowManagerService(ILogger logger) { }
}
It's easy to do something like this:
public class NinjectModuleLoader : NinjectModule
{
public override void Load()
{
this.Bind<IWindowManager>().To<WindowManagerService>().InSingletonScope();
}
}
and successfully configure the dependency injection.
However the problem I run into is when I need to provide a concrete instance of a class into the constructor such as the following example:
public class ObservableLogger : ILogger
{
public ObservableLogger(Dispatcher dispatcher) { }
}
In the above example I require the ability to pass in a concrete implementation of the dispatcher as I cannot use DI to establish this link and must reference the application wide Dispatcher instance.
Essentially what I wish to be able to do is something like this:
this.Bind<ILogger>().To(new ObservableLogger(Dispatcher)).InSingletonScope();
So how does one provide concrete implementations of dependencies to the NInject dependency manager?
You could use a factory method:
this.Bind<ILogger>().ToMethod(context => new ObservableLogger(Dispatcher));
...or create your own custom provider as explained in the docs: https://github.com/ninject/Ninject/wiki/Providers,-Factory-Methods-and-the-Activation-Context
There is also the ToConstant and ToConstructor methods:
this.Bind<ILogger>().ToConstant(new ObservableLogger(Dispatcher));
Please refer to this blog post for more information.
I have an asp.net mvc application and need to call wcf service in it. I've added service reference to the project. I use unity for dependency injection and want to inject wcf client. But it's not so simple because of System.ServiceModel.ClientBase. I did it this way.
This is an autogenerated proxy:
public partial class WcfServiceClient :
System.ServiceModel.ClientBase<WcfUnity.IWcfServiceClient>,
WcfUnity.IWcfServiceClient
{
//autogenerated constructors and methods
}
I created interface:
public interface ISimpleProxy : WcfUnity.IWcfServiceClient
{
//duplication of methods' signatures
void CloseConnection();
}
I extended WcfServiceClient using partial class:
public partial class WcfServiceClient : ISimpleProxy
{
public void CloseConnection()
{
try
{
Close();
}
catch (Exception)
{
Abort();
}
}
}
And inject it like this:
container.RegisterType<ISimpleProxy>(new InjectionFactory(c => new WcfServiceClient()));
So I don't have dependecies from ClientBase and there is no wcf stuff inside classes which use this wcf proxy. Does this solution have some disadvatages?
No, it doesn't, I use (mostly) the same approach.
I would recommend you making your interface inherit from IDisposable, because underlying ClientBase<T> is disposable. This way you won't need CloseConnection.
I having a bit of trouble getting my head around Ioc and generics, and particularly how my company has set up the layers in relation to this. We're working under an MVP architecture.
I have a Car class:
class Car : ICar
{
IList<IWheel> wheels{get;set;}
IEngine engine{get;set;}
string registrationplate {get;set;}
public Car(){}
}
and I want to be able to get a newly created ICar, and I also want to be able to find an ICar by Id. Problem is I'm not sure why some of the design choices have been made in the project I'm working on. The structure for other services already created is as follows:
I have a Car and WHeel Service :
class WheelService : BaseService
{
IWheel wheel;
public IWheel Create()
{
return new wheel()
}
}
class CarService : BaseService
{
WheelService wheelservice;
public ICar CarCreate()
{
wheelservice = new Wheelservice()
car = new Car();
IWheel wheel = wheelservice.Create();
car.wheels.add(wheel);
return car;
}
public ICar Find(int id)
{
return (Car)base.Find<Car>(id);
}
}
Firstly, I'm finding the 'have a service for each entity' odd. I wouldn't have thought that a weak entity would have a service. My thoughts would be that the CarService create method would act like a factory method, without having to call a wheel service.
Also, the wheel service create method is actually used in the presenter code to return an IWheel all the way down to the UI, so that values can be set and passed back up. Again this, seems odd to me. Means the presenter can request the full ICar object from the UI.
Is the dependency in the Service create method normal? I would have thought that this would be brought in through IoC. But, if the ICar Create method was to handle all creation (including wheel, etc), then presumably the container would contain lots of interfaces in relation to this particular service?
If I were to bring in the interfaces, I would need to adjust the CarService.Find method, which is currently using concrete classes. It uses the BaseService, and it is solely this layer which interacts with the container to get the correct repository:
class BaseService
{
private object myRepository;
protected T GetRepository<T>(Type serviceType)
{
if (myRepository == null)
{
myRepository = (T)IoCRepositoryFactory.GetRepositoryInstance(typeof(T), serviceType);
}
return (T)myRepository;
}
protected virtual IGenericRepository Repository
{
get
{
return GetRepository<IGenericRepository>(this.GetType());
}
}
protected virtual T Find<T>(Object id) where T : class
{
return (T)Repository.GetByID<T>(id);
}
}
I'm unsure how to call this find method if I'm only using interfaces, since the current service definition is using concrete classes.
Apologies about this being a long winded post. I've been looking over this for three days, but I need to know what others think of the current set up, and whether I should be using IOC for domain objects in service layer, or whether I should follow the current set up. It just all feels a bit coupled for me at the moment.
There's a lot you're misunderstanding I think.
I'll start with the service structure. You don't have to have each service only handling 1 type of entity, but there's nothing wrong with that as long as it doesn't get in the way of efficiency. Your example is likely unreasonably simplistic, so you probably could have CarService handle Wheel management without any future maintenance issues, but it's common to divide services up by entity and although it often requires some exceptions it usually works fine.
The IoC code you have written is all sorts of wrong though. The goal of IoC is to keep all the code that will be doing your dependency management in a single place that's sort of out of the way. Your code has CarService instantiating WheelService explicitly, while that should be handled by your IoC container. Also, having a GetRepository method is very awkward, and also should be handled automatically by your IoC container.
One way you could setup your services and repositories would be like this (if you're using constructor injection). This is just an example (and a verbose one at that), don't go copying this structure into your own code without fully understanding it.
public interface IRepository {
//Some interfaces
//This method could only really be implemented if you are using an ORMapper like NHibernate
public T FindById<T>(Object id) { }
}
public class BaseRepository : IRepository {
//Some base crud methods and stuff. You can implement this if you're using an ORMapper
public T FindById<T>(Object id)
{
return CurrentSession.FindById<T>(id);
}
}
public class WheelRepository : BaseRepository {
//Wheel crud
//If you don't have an ORMapper because you're a masochist you can implement this here
public Wheel FindById(Object id) { }
}
public class CarRepository : BaseRepository {
//Car crud
//If you don't have an ORMapper because you're a masochist you can implement this here
public Car FindById(Object id) { }
}
public class BaseService {
protected BaseRepository _baseRepository;
//This constructor is automatically called by your IoC container when you want a BaseService
public BaseService(BaseRepository repository)
{
_baseRepository = repository;
}
//More methods
}
public class WheelService : BaseService
{
protected WheelRepository _wheelRepository;
public WheelService(WheelRepository wheelRepo) : base(wheelRepo)
}
public class CarService : BaseService
{
protected WheelService _wheelService;
protected CarRepository _carRepository;
public CarService(WheelService wheelService, CarRepository carRepository)
{
_wheelService = wheelService;
_carRepository = carRepository;
}
}
Since you're using MVP, I assume some kind of WPF/Winforms app, although I suppose you could do a web app as well if you really wanted to make it fit in asp.net. In either case, they both have a single Factory you can configure for creating your presenter classes. In that factory, you'd have it do all the injection there, out of the way in a spot you never have to worry about or even look at after setting it up. That code would just call this:
//Override the default factory method (just made this up)
public override Presenter GetPresenter(Type presenterType)
{
return ComponentFactory.GetInstance(presenterType);
}
Then if you had a presenter that depended on a service, it would automatically be there, and everything that service needs would be there too. Notice how there's no ugly service constructors or factory calls anywhere else. All the dependencies are automagically setup by the container.
I don't know why the code at your company has those awful GetRepository methods. That's an instance of an anti-pattern, because you're replacing what would normally be a constructor call like new Repository() with a GetRepository call instead that's only marginally more maintainable.
You should try playing around with some well-known containers. Structuremap is a pretty good one.
I am getting confused with the scenario of 2 classes implementing the same interface and Dependency Injection.
public interface ISomething
{
void DoSomething();
}
public class SomethingA : ISomething
{
public void DoSomething()
{
}
}
public class SomethingAB : ISomething
{
public void DoSomething()
{
}
}
public class Different
{
private ISomething ThisSomething;
public Different(ISomething Something)
{
ThisSomething = Something;
}
}
I have seen online examples say that this is valid but you would only use one class at a time. So if the app is running at SiteA you tell your IOC to use SomethingA but if its at SiteB you tell it to use SomethingAB.
Is it considered bad practice therefore to have one app that has 2 classes that implement 1 interface and for it to try to use both classes? If its not how do you tell the IOC which class to use in the relevant circumstance?
UPDATE: To explain it better I will use Ninject's example:
public class Samurai
{
private IWeapon Weapon;
public Samurai(IWeapon weapon)
{
this.Weapon = weapon;
}
}
public class Sword : IWeapon
{
...
}
public class Gun : IWeapon
{
...
}
public class WarriorModule : NinjectModule
{
public override void Load()
{
this.Bind<IWeapon>().To<Sword>();
this.Bind<IWeapon>().To<Gun>(); //Just an example
}
}
So now you have 2 classes that use IWeapon. Depending on something or a context in your app you want Samurai to have a Sword sometimes or a Gun at other points. How do you make this happen? How do you handle that "if" scenario??
I don't think that this is a bad practice in the general case. There are situations where you could need different implementations of the same interface inside the same application and based on the context use one or another implementation
As far as how to configure your DI to enable this scenario, well, it will depend on your DI of course :-) Some might not support it, others might not, others might partially support it, etc..
For example with Ninject, you could have the following classes:
public interface ISomething
{
}
public class SomethingA : ISomething
{
}
public class SomethingB : ISomething
{
}
public class Foo
{
public Foo(ISomething something)
{
Console.WriteLine(something);
}
}
public class Bar
{
public Bar(ISomething something)
{
Console.WriteLine(something);
}
}
and then use named bindings when configuring the kernel:
// We create the kernel that will be used to provide instances when required
var kernel = new StandardKernel();
// Declare 2 named implementations of the same interface
kernel.Bind<ISomething>().To<SomethingA>().Named("somethingA");
kernel.Bind<ISomething>().To<SomethingB>().Named("somethingB");
// inject SomethingA into Foo's constructor
kernel.Bind<Foo>().ToSelf().WithConstructorArgument(
"something", ctx => ctx.Kernel.Get<ISomething>("somethingA")
);
// inject SomethingB into Bar's constructor
kernel.Bind<Bar>().ToSelf().WithConstructorArgument(
"something", ctx => ctx.Kernel.Get<ISomething>("somethingB")
);
Now when you request an instance of Foo it will inject SomethingA into it its constructor and when you request an instance of Bar it will inject SomethingB into it:
var foo = kernel.Get<Foo>();
var bar = kernel.Get<Bar>();
i worked with Unity and spring in this context and i think that interest lies in having a weak coupling between packages, ie classes, the ability to change service or point of entry is a consequence of the ioc.
ioc provides flexibility in the use of service, or from the time the services implement the same interface,
If Utilize Service A Service B and Service is in the service package A and package B is in B.
Package A has no reference on the package b, but the service A has a reference on the package containing the interfaces.
Therefore we conclude that we have a weak coupling between package A and package b.
Having multiple implementations mapped to the same interface isn't really bad practice, but it isn't he most common usage pattern.
You didn't specify a specific DI tool, but if you use Unity, you can do this with named instances. See here: Unity - how to use multiple mappings for the same type and inject into an object
maybe this is easy, but searching it on the internet already give me a head ache
here is the problem:
interface IValidator
{
void Validate(object obj);
}
public class ValidatorA : IValidator
{
public void Validate(object obj) { }
}
public class ValidatorB : IValidator
{
public void Validate(object obj) { }
}
interface IClassA { }
interface IClassB { }
public class MyBaseClass
{
protected IValidator validator;
public void Validate()
{
validator.Validate(this);
}
}
public class ClassA : MyBaseClass, IClassA
{
//problem: validator should ValidatorA
public ClassA(IValidator validator) { }
}
public class ClassB : MyBaseClass, IClassB
{
//problem: validator should ValidatorB
public ClassB(IValidator validator) { }
}
public class OtherClass
{
public OtherClass(IClassA a, IClassB b) { }
}
//on Main
var oc = container.Resolve<OtherClass>();
Any idea?
EDIT
I registered ValidatorA and ValidatorB with Named, now the problem how Castle Windsor can inject those validator properly to the ClassA and ClassB, is there a way to do that? or is there any better solution?
if there is someone think my class design is wrong please, i open for any advice. So far i think it correct. Yes, validator have specific configuration for specific Class. but there are reasons it is abstracted:
Validator is a complex object, sometime should connect to database, so I MUST pass interface instead of implementation to constructor for unit testing reason.
No way to use different interface for any of Validator, because the only method that i used is Validate
I think MyBaseClass.Validate() a common template method pattern isn't it?
Without going into the details of your chosen architecture just focusing on the Windsor container configuration:
If you have registered multiple named implementation to a given interface (IValidator), you can specify which one do you want to use when registering the consumer classes (ClassA, ClassB) with using ServiceOverrides:
The following container configuration providers an OtherClass with ClassA instance with a ValidatorA and ClassB instance with a ValidatorB:
var container = new WindsorContainer();
container.Register(Component.For<IClassA>().ImplementedBy<ClassA>()
.DependsOn(ServiceOverride.ForKey<IValidator>().Eq("ValidatorA")));
container.Register(Component.For<IClassB>().ImplementedBy<ClassB>()
.DependsOn(ServiceOverride.ForKey<IValidator>().Eq("ValidatorB")));
container.Register(Component.For<IValidator>().ImplementedBy<ValidatorA>()
.Named("ValidatorA"));
container.Register(Component.For<IValidator>().ImplementedBy<ValidatorB>()
.Named("ValidatorB"));
container.Register(Component.For<OtherClass>().ImplementedBy<OtherClass>());
var oc = container.Resolve<OtherClass>();
It appears that you're trying to put tight couples (ClassA with ValidatorA, ClassB with ValidatorB) as independent types into a common container. This is pointless. If you must rely on tight coupling like this, forget dependency injection in this regard and just hard-reference the types.
This would make more sense if you could implement a common validator for all classes. For instance, make the classes responsible for providing validation rules, and let Validator
just enforce the rules. Or perhaps just include the whole validation inside your classes, which is probably the most sensible scenario here.
MyBaseClass.Validate() look like inversion of control, but not like a template method.