Extra methods in drived class of abstract class - c#

I am aware that this question has been asked many times. But looking at the answers I couldn't find the right one or working one that suits me.
Let's say I have an abstract class
public abstract class EntityService<T>
{
public T GetAll()
{
//Implementation
}
}
Then I have a drived class
public class UserService : EntityService<User>
{
public User GetAll(string Orderby)
{
//Implementation
}
}
And I create a static variable of the UserService for to use it through out my project.
public static readonly EntityService<User> UserService = new UserService();
Using UserService.GetAll(); would work perfectly fine. However when I want to use UserService.GetAll("Acsending"); would given an compiler error saying this method does not exist. I know I have to cast it to UserService Type but I couldn't do it. Where I put (UserService) It always gave errors and I am wondering is there a better way to do this without casting it since I want to write my code plain and simple as possible.

I think for your situation will be useful to do it like this, sorry that a little bit late, but:
public interface IUserService
{
User GetAll();
User GetAll(string OrderBy);
}
public abstract class EntityService<T>
{
public T GetAll()
{
//Implementation
}
}
public class UserService : EntityService<User>, IUserService
{
public User GetAll(string OrderBy)
{
//Implementation
}
}
And then use it like this:
public static readonly IUserService UserService = new UserService();
....
UserService.GetAll();
UserService.GetAll("orderByColumn");
And then if you want some common code for Entities, you can write something like this:
void ForEntityMethod(EntityService<T> entityService)
If special for Users i.e.:
void ForUserMethod(IUserService userService)
It think it give you more flexibility and avoid cast in your situation.
Also exist another good variants, but they are can be used if you have some future vision of system.

You need to either declare the variable as the subclass like this:
public static readonly UserService userService = new UserService();
Or, you downcast every time you want to use the EntityService<User> as UserService:
var userServiceDownCast = (UserService)userService;
userServiceDownCast.GetAll("Ascending");

Related

Autofac inject IEnumerable of generic interfaces

So, I recognize StackOverflow is littered with this question, but frequently no one explains why they want to do this. I'm hoping that by doing so a better answer floats to the top.
This guy did something close to what I want: Resolving IEnumerable of generic interfaces from Autofac container But not quite.
I recognize IGenericInterface<ObjectA> is not equivalent to IGenericInterface<ObjectB>.
That being said, I'd love to inject every IService<T> into a single constructor so that I can build a lookup. Honestly, I'd like to build an implementation very similar to DbContext.Set<T>
A few key players in my problem.
public interface IService<TMessage> where TMessage: IContractDTO
{
IQueryable<TMessage> BuildProjection();
}
Currently I'm injecting these one at a time
public class SomeController : BaseODataController<SomeEntityDTO>
{
public SomeController(IControllerServiceContext context, IService<SomeEntityDTO> service)
: base(context, service)
{
}
//DO STUFF
}
IControllerServiceContext is a composite interface with DbContext, AppSettings, and a few other common goodies I want in every controller.
In most cases this is good enough. However occasionally in support of logic for EntityA, I might need to do a quick lookup on B. I'd rather use IService<SomeEntityB>'s implementation of BuildProjections() than building out a redundancy in Controller A. If I inject each one I have a few that would become an 8 or 9 param constructor this way, for example
SO I got to thinking what if I was able to add an IServiceLookup to IControllerServiceContext then I would have everything I needed.
I Started down this path:
public class ServiceLookup<TContract>: IServiceLookup where TContract: BaseClass, IContractDTO
{
public ServiceLookup(IEnumerable<IService<TContract>> services)
{
//Build _Services
}
private readonly IDictionary<Type, object> _services;
public IService<TMessage> Service<TMessage>() where TMessage : class, IContractDTO
{
return (IService<TMessage>)(GetService(typeof(TMessage)));
}
private object GetService(Type type)
{
_services.TryGetValue(type, out var service);
return service;
}
}
For obvious reasons this can't be done with the current constructor.
But is there a way to get the dictionary that I do want, either by IIndex or an IEnumerable that I can build that dictionary of <type, object> where object is my various IService<T>?
Service lookup was built based on reading the DbContext code and simplifying the logic for DbContext.Set, which is also driven by IDictionary<Type, object>.
If through some kind of resolver parameter I can get all the IService<T>s, Extract the T types, and add them to that list, I'm off to the races.
Edit: I recognize I could inject the parameters I need to build each service
into ServiceLookup and manually build my list, and that may even be the better answer... but if I can do it without all that, it would be a lot more robust, and I'm fundamentally curious if it is possible
Edit2: What I want to be able to do in implementation would look like this:
public SomeController(IControllerServiceContext context, IServiceLookup lookup)
: base(context, service)
{
public SomeMethod() {
var x = lookup.Service<EntityOneDTO>().BuildProjections().FirstOrDefault();
var y = lookup.Service<EntityTwoDTO>().BuildProjections().FirstOrDefault();
//Do Logic that requires both EntityOne and EntityTwo
}
}
Let's assume you have the following types :
public class MessageA { }
public class MessageB { }
public interface IService<TMessage> { }
public class ServiceA : IService<MessageA> { }
public class ServiceB : IService<MessageB> { }
And you have a controller and you want to get a IService<MessageA> based on whatever you want.
The first solution would be to inject all IService you may required :
public class Controller
{
public Controller(IService<MessageA> serviceA, IService<MessageB> serviceB)
{
this._serviceA = serviceA;
this._serviceB = serviceB;
}
private readonly IService<MessageA> _serviceA;
private readonly IService<MessageB> _serviceB;
public void Do()
{
IService<MessageA> serviceA = this._serviceA;
}
}
It works if you have few message type but not if you have more than few.
because IService<T> is generic and Do there is no easy way to mix both world. The first solution would be to introduce a non generic interface
public interface IService { }
public interface IService<TMessage> : IService { }
and register these type like this :
builder.RegisterType<ServiceA>().As<IService<MessageA>>().As<IService>();
builder.RegisterType<ServiceB>().As<IService<MessageB>>().As<IService>();
Then you can have an IEnumerable<IService>. Something like that :
public interface IServiceLookup
{
IService<TMessage> Get<TMessage>();
}
public class ServiceLookup : IServiceLookup
{
public ServiceLookup(IEnumerable<IService> services)
{
this._services = services
.ToDictionary(s => s.GetType()
.GetInterfaces()
.First(i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IService<>))
.GetGenericArguments()[0],
s => s);
}
private readonly Dictionary<Type, IService> _services;
public IService<TMessage> Get<TMessage>()
{
// you should check for type missing, etc.
return (IService<TMessage>)this._services[typeof(TMessage)];
}
}
and then inject IServiceLookup inside your controller.
The drawback of this solution is that it create instances of all your IService, to avoid that you can inject IEnumerable<Func<IService>>
Another solution would be to inject IComponentContext to ServiceLookup. ComponentContext is an Autofac type from where you can resolve services.
public class ServiceLookup : IServiceLookup
{
public ServiceLookup(IComponentContext context)
{
this._context = context;
}
private readonly IComponentContext _context;
public IService<TMessage> Get<TMessage>()
{
return this._context.Resolve<IService<TMessage>>();
}
}

How to bind decorators with Ninject from outside in?

I use ninject bindings with WhenInjectedInto<> to bind decorators from inside out. However, from different entry points I need different features, maybe run in different sequence, so I would like to bind the decorators chain from outside in. Is this possible with Ninject?
Eg. I would live to achieve this:
Bind<IFooService>().To<SimpleService>().WhenInjectedInto<FeatureAFooServiceDecorator>();
Bind<IFooService>().To<FeatureAFooServiceDecorator>().WhenInjectedInto<FeatureBFooServiceDecorator>();
Bind<IFooService>().To<FeatureBFooServiceDecorator>().WhenInjectedInto<EntryPoint1>();
Bind<IFooService>().To<SimpleService>().WhenInjectedInto<FeatureBFooServiceDecorator>();
Bind<IFooService>().To<FeatureBFooServiceDecorator>().WhenInjectedInto<EntryPoint2>();
But this is not correct, because FeatureBFooServiceDecorator is not clear what it will get injected (FeatureAFooServiceDecorator or SimpleService).
I suppose the solution would be to get things binded the other way round like:
pseudocode
For<EntryPoint1>().Use<FeatureBFooServiceDecorator>().ThenUse<FeatureAFooServiceDecorator>().ThenUse<SimpleService>();
For<EntryPoint2>().Use<FeatureBFooServiceDecorator>().ThenUse<SimpleService>();
Edit:
To achieve this manually, I would do:
var entryPoint1 = new EntryPoint1(new FeatureBFooServiceDecorator(new FeatureAFooServiceDecorator(new SimpleService)));
var entryPoint2 = new EntryPoint2(new FeatureBFooServiceDecorator(new SimpleService));
(Of course I would avoid newing up things, because these classes have couple of more dependencies each, some of which are InRequestScope or InNamedScope)
Note: For the above example, asume that there are these classes:
public interface IFooService {/*...*/}
public class SimpleService : IFooService {/*...*/}
public class FeatureAFooServiceDecorator : IFooService
{
private readonly IFooService _innerFooService;
public FeatureAFooServiceDecorator(IFooService fooService) {
_innerFooService = fooService;
}
}
public class FeatureBFooServiceDecorator : IFooService {/*...same as above...*/}
public class EntryPoint1{
public EntryPoint1(IFooService fooService){/*...*/}
}
public class EntryPoint2{
public EntryPoint2(IFooService fooService){/*...*/}
}
So i gather what you want to do is
public class FeatureBFooService : IFooService
{
public FeatureBFooService(IFooService service1, IFooService service2)
{ ...}
}
var service = new FeatureBFooService(new FeatureAFooService(), new SimpleService());
(of course you don't want to do the new's yourself). So you are using the same interface multiple times, even for the same constructor, but want not only different instances but different types (FeatureAFooService, SimpleService) injected into the constructor of FeatureBFooService.
There's two ways i can think of how you can achieve this.
But to be honest, i ought to warn you that this seems quite complicated. Usually this means the design is not ideal and you'd be better of thinking about how to solve the problem differently. After all, when the implementation share the same interface, shouldn't they be doing about the same thing? It would be one thing to inject a collection of IFooService into a class whose using all these services, but that that class itself again is a IFooService seems a bit strange.
But enough said, i believe in people making their own choices - and sometimes mistakes - because that's the best way to learn. And of course i may also be wrong in my assumptions and what you're striving for is the best achievable solution.
Solution 1: .ToConstructor() binding
Bind<IFooService>().ToConstructor(ctorArg => new FeatureBFooService(ctorArg.Inject<FeatureAFooService>(), ctorArg.Inject<SimpleService>()));
for every constructor parameter you can define what should get injected. This way you don't rely on a binding and can determine what get's injected for a given type.
Solution 2: [Named] binding
adapt the implementation as follows:
public const string FeatureAService = "FeatureA";
public const string SimpleService = "Simple";
public class FeatureBFooService : IFooService
{
public FeatureBFooService(
[Named(FeatureAService)]I FooService service1,
[Named(SimpleService] IFooService service2)
{ ...}
}
Bind<IFooService>().To<FeatureAService>().Named(FeatureAService);
Bind<IFooService>().To<SimpleService>().Named(SimpleService);
Solution 3: .ToProvider() binding + custom binding logic
What you could also do, is to do
Bind<IFooService>().ToProvider<FooServiceProvider>();
where FooServiceProvider will - according to you custom logic - decide what exact dependency is to be instanciated. It could then either do
IResolutionRoot.Get<FeatureAFooService>();
or you could still make use of the [Named] feature:
IResolutionRoot.Get<IFooService>(FeatureAService);
It could then, for example, look like (pseudo code):
public class FooServiceProvider : Provider<IFooService>
{
protected override IFooService CreateInstance(IContext context)
{
Type returnType = DetermineImplementationType(context);
switch(returnType)
{
case typeof(FeatureBFooService):
return CreateFeatureBFooService(context);
break:
default:
throw new NotSupportedException(...);
}
}
private static Type DetermineImplementationType(IContext context)
{
// your custom logic here
}
private static IFooService CreateFeatureBFooService(IContext context)
{
var dependency1 = context.Kernel.Get<IFooService>(FeatureAFooService);
var dependency2 = context.Kernel.Get<IFooService>(SimpleService);
return context.Kernel.Get<IFooService>(
FeatureBFooService,
new ConstructorArgument("service1", dependency1),
new ConstructorArgument("service2", dependency2));
}
}
Note that with ConstructorArgument, the value is injected into the constructor parameter matching the name (service1, service2), so that's a refactor-trap.
Also note that you can also use IContext.Kernel.ContextPreservingGet<> if you need to preserve the context. However, that's only available with the extension ninject.extensions.ContextPreservation.

Unit Of Work Pattern - Getting repositories with a factory

I am following a tutorial to do with the Repository Pattern in a combination with the Unit Of Work pattern.
I essentially have:
interface IRepository<T> where T : class
{
//...
}
class Repository<T> where T : class
{
//Implemented methods
}
interface IFooRepository
{
IQueryable<Foo> GetFoos();
}
class FooRepository : Repository<Foo>, IFooRepository
{
IQueryable<Foo> GetFoos() {}
}
The above represents my repositories, in a basic sense. I then have a Uow class.
public class MyUow
{
public void Commit() { }
public IRepository<Bar> Bars { get { return GetStandardRepo<Bar>(); } }
public IFooRepository Foos { get { return GetRepo<IFooRepository>(); } }
private IRepository<T> GetStandardRepo()
{
return RepositoryProvider.GetRepoistoryForEntityType<T>();
}
private T GetRepo<T>()
{
return RepositoryProvider.GetRepository<T>();
}
}
My problem is coming where the tutorial I am following only ever instansiates a Dictionairy<Type, object> in the RepositoryProvider class and doesn't seem to fill it, so the method used in GetRepo<T> doesn't work.
public virtual T GetRepository<T>(Func<DbContext, object> factory = null) where T : class
{
//Look for T in the dictionairy by typeof(T)
object repoObj;
Repositories.TryGetValue(typeof(T), out repoObj);
if (repoObj != null)
return (T)repoObj;
//Not found or a null value, make a new instance of the repository.
return MakeRepository<T>(factory, Context);
}
private T MakeRepository<T>(Func<DbContext, object> factory, DbContext dbContext) where T : class
{
var f = factory ?? _repositoryFactories.GetRepositoryFactory<T>();
if (f == null)
//Exception here because this is null
throw new NotImplementedException("No factory for repository type");
var repo = (T)f(dbContext);
Repositories[typeof(T)] = repo;
return repo;
}
My question is essentially what is the correct way to implement this pattern and where I am going wrong? Should I instansiate the Dictionairy<Type, Func<DbContext, object> with a the list of known repositories? This seems dirty. I am driving myself insane trying to solve this!
Thanks in advance.
What I see from beginning is that your Repository<T> doesn't implement IRepository<T>, so it should be like this:
class Repository<T> : IRepository<T> where T : class
{
//Implemented methods
}
Then your completely secret tutorial should describe how _repositoryFactories.GetRepositoryFactory<T>() can discover your IRepository<T> implementor FooRepository - maybe it willbe autodiscovery, maybe you need to register something somewhere.
Next, again I know nothing about your specific tutorial and factories etc, but I suppose you may need to use GetRepo<Foo> instead of GetRepo<IFooRepository>, because right now this IFooRepository looks meaningless... or maybe again you miss something in this IFooRepository declaration, and it should be like interface IFooRepository : IRepository<Foo> - and again, it greatly depends on particular discovery implementation for factories you are using.
In case you have not found the answer yet, I followed through the tutorial and was able to run it (the tutorial sample). If you're sure that you have implemented it right, take note of this,
The Repository Dictionary is by default, null and will only have value of the not standard repos (e.g. IFooRepository) when it is first requested. Therefore, if you're checking the value in debug of the Repository Dictionary and an IFooRepository is not yet requested it is for sure that you will not see it there. Have a code to access the IFooRepository first then it will make a repository for that in the MakeRepository method of the provider class.
Hope that helps
There is a helper class called RepositoryFactories.cs
You need to add an entry for your custom Repository to the dictionary
{typeof(IFooRepository ), dbContext => new FooRepository (dbContext)}

Generics problem with Unit of Work Pattern

I need some help with the design of the Unit of Work + Repository + IoC pattern. I have several interfaces defined as follows:
public interface IRepository<T>
{
T GetEntity(int id);
}
public interface IUserRepository : IRepository<User>
{
User GetUserByXyz(int id);
}
public interface IUnitOfWork
{
T Respository<T>() where T : IRepository<T>;
}
I am using Unity to resolve some references. Here's the implementation of the UoW:
public class UnitOfWork : IUnitOfWork
{
public T Respository<T>() where T : IRepository<T>
{
var container = new UnityContainer();
return container.Resolve<T>();
}
}
Now i am having trouble calling the interface:
User user = _unitOfWork.Respository<IUserRepository>().GetUserByXyz(1);
The type 'IUserRepository' cannot be used as type parameter 'T' in
the generic type or method 'IUnitOfWork.Respository()'. There is no
implicit reference conversion from 'IUserRepository' to
'IRepository'.
How do get around the generic constraint error?
Expanding on my comment:
The statement public T Respository<T>() where T : IRepository<T> implies that you're expecting a type that is a Repository of itself, e.g. IUserRepository would have to be an IRepository<IUserRepository> to satisfy your condition.
You need two different generics, one for the item that is held in the reporsitory TItem and another for the repository itself, TRepo.
Then the whole code becomes:
public interface IRepository<TItem>
{
TItem GetEntity(int id);
}
public interface IUserRepository : IRepository<User>
{
}
public interface IUnitOfWork
{
TRepo Respository<TRepo,TItem>() where TRepo : IRepository<TItm>;
}
and
public class UnitOfWork : IUnitOfWork
{
public TRepo Respository<TRepo,TItem>() where TRepo : IRepository<TItem>
{
var container = new UnityContainer();
return container.Resolve<TRepo>();
}
}
finally, the call becomes:
User user = _unitOfWork.Respository<IUserRepository,User>().GetEntity(1);
Initial note:
_unitOfWork.Respository<IUserRepository>()…
As it is, you're essentially "abusing" UnityOfWork as a service locator (you can ask it for any type of repository), but it doesn't seem to offer any additional benefits. Is this really what you want? Couldn't you just do away with UnitOfWork and do the following instead:
_unityContainer.Resolve<IUserRepository>()…
Alternative solution that does not require a second type parameter:
I agree with #Jon Egerton that for this to work correctly, one option would be to introduce a second generic type parameter (TItem next to TItemRepository). There is, however, another solution involving a marker interface IRepository:
// non-generic marker interface (empty)
public interface IRepository {}
public interface IRepository<T> : IRepository { … /* as before */ }
// ^^^^^^^^^^^^^
// added
public class UnitOfWork
{
public TRepository Get<TRepository>() where TRepository : IRepository
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// this way, no 2nd type parameter is
// needed since the marker interface is
// non-generic.
{
return new UnityContainer().Resolve<TRespository>();
}
}
As requested: Unit of Work example:
If you follow Martin Fowler's definition for the Unit of Work pattern, you get something rather different from what you've got right now. Rather, a Unit of Work according to his udnerstanding merely keeps track of all changes that have been made to a collection of objects. The idea behind this is that changes aren't persisted (e.g. to a database) one at a time, but all at the same time, when requested through the unit of work object; thus the pattern's name:
class UnitOfWork<T>
{
// the UnitOfWork object tracks changes to objects of type T:
private HashSet<T> newItems;
private HashSet<T> modifiedItems;
private HashSet<T> removedItems;
public void Commit()
{
// let's say items are persisted to an RDBMS, then:
// * generate 'DELETE FROM [tableForItemsOfTypeT]' statements
// for all items in the 'removedItems' set;
// * generate 'INSERT INTO [tableForItemsOfTypeT]' statements
// for all items in the 'newItems' set;
// * generate 'UPDATE [tableForItemsOfTypeT]' statements
// for all items in the 'modifiedItems' set.
}
}
Your definition of IUnitOfWork seems a little peculiar, and it seems you've got your generic parameter constraint wrong:
public interface IUnitOfWork
{
T Respository<T>() where T : IRepository<T>;
}
I'd try to get rid of the generic parameter constraint, if possible. For example:
public interface IUnitOfWork<T>
{
IRepository<T> Respository { get; }
}
public class UnitOfWork<T> : IUnitOfWork<T>
{
public IRepository<T> Respository
{
get
{
var container = new UnityContainer();
return container.Resolve<IRepository<T>>();
}
}
}
(Admittedly, I'm not sure whether it's a good idea to constrain a UnitOfWork class to one particular object type by parameterizing it this way. You could in theory also have a UnitOfWork class that implements IUnitOfWork<T> several times, for different T, though that's probably equally unwise. Judge yourself what is most appropriate for your purposes.)
Note that you'd then also have to register your types differently. You could possibly also get rid of IUserRepository this way.
P.S.: Probably, Repository does make more sense if it's a method, and not a property, as shown above. I'd choose based on how costly it is to "get" a repository. If it's expensive, make it a method; if it's a cheap operation, a property might be just fine. If you keep it as a method, I'd rename it to GetRepository to better adhere to the common .NET naming guidelines. Alternative approach:
public interface IUnitOfWork
{
IRepository<T> GetRespository<T>()
}
You are confusing your Generic constraint:
public T Respository<T,U>() where T : IRepository<U>
User user = _unitOfWork.Respository<IUserRepository,User>().GetEntity(1);

C# Generics and abstract factory pattern - or some way of doing something similar

I am trying to write a sort of extendable data layer for my application One of the "repositories" is an in-memory implementation of my abstract store class
public abstract class Store<TEntity, TIdentifier> : IStore<TEntity, TIdentifier>
where TEntity : StorableEntity<TIdentifier>
{
//abstract methods here
public abstract TIdentifier GetUniqueIdentifier();
}
The "StorableEntity" abstract class is:
public abstract class StorableEntity<TIdentifier>
{
public TIdentifier ID { get; set; }
}
I have a concrete class of Store called "InMemoryStore" that looks like this:
public class InMemoryStore<T, U> : Store<T, U>
where T : StorableEntity<U>
{
protected static Dictionary<U, T> store = new Dictionary<U, T>();
public override U GetUniqueIdentifier()
{
// call relevant "generator" here - SOMETHING LIKE THIS??
// var generator = GetGeneratorSomehow(U);
// return generator.Create();
}
}
Now, the type of "U" here could be string, int, Guid etc...
(most of the time it could be int)
My idea here is to create something like an IUIDGenerator like this:
public interface IUIDGenerator<T>
{
T Create(ICollection<T> collection);
}
In the above "InMemoryStore" i would then create an instance of an IUIDGenerator, pass in the store dictionarys key collection, and call the "Create" method to return a unique identifier of the required type.
For example, i could have an IntUIDGenerator class like this (that would act as a kind of incremental number generator, based on the numbers already in the dictionary keys)
public class IntUIDGenerator : IUIDGenerator<int>
{
public int Create(ICollection<int> collection)
{
var result = collection.Max() + 1;
if (collection.Contains(result))
return result;
throw new NotUniqueException();
}
}
Actual Question:
What I need to do, is within InMemoryStore, identify the type of U (the type of the identifier) and be able to dynamically select the required concrete implementation of IUIDGenerator - how can i do this?
I thought about having a type of class factory pattern - loading all the available UIDGenerators into a dictionary... but they can all have different types?
Is there a better way around this?
Also, I am aware the title of my question may be a bit off - if anyone has a better suggestion, please feel free to comment and I'll change it.
You could use an IoC framework, such as Unity, Castle, Ninject, etc. Then you'd configure your container with something like the following:
_container = new UnityContainer();
_container.RegisterType<IUIDGenerator<int>, IntUIDGenerator);
_container.RegisterType<IUIDGenerator<Guid>, GuidUIDGenerator);
Then in your class you've have something like the following:
public override U GetUniqueIdentifier()
{
var generator = _container.Resolve<IUIDGenerator<U>>();
return generator.Create();
}
I think you'll have to use at least one cast. If you store all your generators in a map like
Map<Type, object> generators;
you can use
class InMemoryStore<T,U> {
public override U GetUniqueIdentifier() {
var generator = generators[typeof(U)] as IUIDGenerator<U>;
return generator.Create(collection);
}
}
Of course, I omitted all sort of validation code :) (like checking, if a generator for type U is in the map etc...)
The short answer: Use dependency injection, and let your DI container handle it for you.
You could add an additional generic type argument for the generator, eg
public class InMemoryStore<T, U, V> : Store<T, U>
where T : StorableEntity<U>
where V : IUIDGenerator<U>, new() {
public override U GetUniqueIdentifier()
{
return (V)(Activator.CreateInstance<V>()).Create();
}
}

Categories

Resources