in my implementation, I have an interface as: ICachingManager. I've got now one implementation. I also created a manager class as:
public class CachingManager
{
#region Members
private ICachingManager service;
#endregion
#region Constructors
public CachingManager(ICachingManager service)
{
this.service = service;
}
#endregion
#region Public Methods
public void EnCache<T>(string key, T value)
{
this.service.EnCache<T>(key, value);
}
public T DeCache<T>(string key)
{
return this.service.DeCache<T>(key);
}
#endregion
}
In case I had one implementation, then I can easily register the CachingManager class with Unity, automatically Unity resolves and injects the ICachingManager.
In case I had more than one implementation using named types, then how can I can make use of Unity? Do I need to make use of an Abstract Factory to decide on which named type to initialize?
Is it a good idea to make use of such a composite class or use directly implementations of the interface with Abstract Factory?
You don't have to create an abstract factory. You can inject a given named implementation:
public class MyClient
{
[Dependency("NamedManager")]
public ICachingManager CachingManager { get; set; }
// or in the constructor
public MyClient([Dependency("NamedManager")] ICachingManager cachingManager) {
// ...
}
}
or you can configure the container to do the same thing:
public class MyClient
{
public MyClient(ICachingManager cachingManager) {
// ...
}
}
...
void ContainerBuilder() {
...
Container.RegisterType<MyClient>(
new InjectionConstructor(
new ResolvedParameter<ICachingManager>("NamedManager")));
...
}
Related
I have a singleton service class
public class Globals
{
public string serverURL { get; set; } = "";
public string hostURL { get; set; } = "";
}
and I have registered it in the Main function:
builder.Services.AddSingleton<Services.Globals>();
anyway I would like to access it from the rest of the Classes in the project, not only the razor pages.
For instance I have a class inside a PCL library:
public class MyStuff
{
public MyStuff()
{
- How do I access Globals in here?!
}
public void MyStuffMethod()
{
- How do I access Globals in here?!
}
}
How to access a Singleton object from the rest classes in the project ?
Access like this, you just need to add a parameter in constructor of class.
public class HomeController : Controller
{
private Globals _globals;
public HomeController(Globals globals)
{
_globals = globals;
}
}
I am newbie to MVC3 application development, currently, we need following Application technologies as requirement
MVC3 framework
IOC framework – Autofac to manage object creation dynamically
Moq – Unit testing
Entity Framework
Repository and Unit Of Work Pattern of Model class
I have gone through many article to explore an basic idea about the above points but still I am little bit confused on the “Repository and Unit Of Work Pattern “. Basically what I understand Unit Of Work is a pattern which will be followed along with Repository Pattern in order to share the single DB Context among all Repository object, So here is my design :
IUnitOfWork.cs
public interface IUnitOfWork : IDisposable
{
IPermitRepository Permit_Repository{ get; }
IRebateRepository Rebate_Repository { get; }
IBuildingTypeRepository BuildingType_Repository { get; }
IEEProjectRepository EEProject_Repository { get; }
IRebateLookupRepository RebateLookup_Repository { get; }
IEEProjectTypeRepository EEProjectType_Repository { get; }
void Save();
}
UnitOfWork.cs
public class UnitOfWork : IUnitOfWork
{
#region Private Members
private readonly CEEPMSEntities context = new CEEPMSEntities();
private IPermitRepository permit_Repository;
private IRebateRepository rebate_Repository;
private IBuildingTypeRepository buildingType_Repository;
private IEEProjectRepository eeProject_Repository;
private IRebateLookupRepository rebateLookup_Repository;
private IEEProjectTypeRepository eeProjectType_Repository;
#endregion
#region IUnitOfWork Implemenation
public IPermitRepository Permit_Repository
{
get
{
if (this.permit_Repository == null)
{
this.permit_Repository = new PermitRepository(context);
}
return permit_Repository;
}
}
public IRebateRepository Rebate_Repository
{
get
{
if (this.rebate_Repository == null)
{
this.rebate_Repository = new RebateRepository(context);
}
return rebate_Repository;
}
}
}
PermitRepository .cs
public class PermitRepository : IPermitRepository
{
#region Private Members
private CEEPMSEntities objectContext = null;
private IObjectSet<Permit> objectSet = null;
#endregion
#region Constructors
public PermitRepository()
{
}
public PermitRepository(CEEPMSEntities _objectContext)
{
this.objectContext = _objectContext;
this.objectSet = objectContext.CreateObjectSet<Permit>();
}
#endregion
public IEnumerable<RebateViewModel> GetRebatesByPermitId(int _permitId)
{
// need to implment
}
}
PermitController .cs
public class PermitController : Controller
{
#region Private Members
IUnitOfWork CEEPMSContext = null;
#endregion
#region Constructors
public PermitController(IUnitOfWork _CEEPMSContext)
{
if (_CEEPMSContext == null)
{
throw new ArgumentNullException("Object can not be null");
}
CEEPMSContext = _CEEPMSContext;
}
#endregion
}
So here I am wondering how to generate a new Repository for example “TestRepository.cs” using same pattern where I can create more then one Repository object like
RebateRepository rebateRepo = new RebateRepository ()
AddressRepository addressRepo = new AddressRepository()
because , what ever Repository object I want to create I need an object of UnitOfWork first as implmented in the PermitController class. So if I would follow the same in each individual Repository class that would again break the priciple of Unit Of Work and create multiple instance of object context.
So any idea or suggestion will be highly appreciated.
Thank you
Your IUnitOfWork interface has too many responsibilities. Each time you add a new repository, you would need to change your IUnitOfWork interface and all of its implementations.
Instead, how about something like this?
public interface IUnitOfWork
{
int SaveChanges();
}
You can then implement this interface in your Entity Framework ObjectContext or DbContext:
public MyCustomContext : DbContext, IUnitOfWork
{
// ... this class already implements the SaveChanges method
}
You can then constructor inject the unit of work into each of your repositories. AutoFac can make certain the same instance is shared among multiple repositories used within the same HttpContext:
public class PermitRepository : IPermitRepository
{
#region Private Members
private readonly IObjectSet<Permit> _objectSet;
private readonly IUnitOfWork _unitOfWork;
#endregion
#region Constructors
public PermitRepository(IUnitOfWork unitOfWork, IObjectSet<Permit> objectSet)
{
_unitOfWork = unitOfWork;
_objectSet = objectSet;
}
#endregion
public IEnumerable<RebateViewModel> GetRebatesByPermitId(int _permitId)
{
// need to implment
}
}
Then, when you constructor inject the repository into the controller, the IUnitOfWork will automatically be constructor injected into the repository.
public class PermitController : Controller
{
#region Private Members
private readonly IPermitRepository _permitRepos;
#endregion
#region Constructors
public PermitController(IPermitRepository permitRepos)
{
if (permitRepos== null)
{
throw new ArgumentNullException("permitRepos");
}
_permitRepos = permitRepos;
}
#endregion
}
Note that when querying data out of your repository, you're really not doing any work, so the IUnitOfWork interface does not apply here. It applies when inserting, updating, and deleting entities, not when selecting them.
I am learning ServiceStack and developing simple demo for helloworld, but could not find namespace for ISservice interface, my code as per below:
public class Hello
{
public string name { get; set; }
}
public class HelloResponse
{
public string Result { get; set; }
}
public class HelloService : **IService**<Hello>
{
public object Execute(Hello request)
{
return new HelloResponse { Result = "Hello" + request.name };
}
}
public class HelloAppHost : AppHostBase
{
public HelloAppHost() : base("Hello Web Services", typeof(HelloService).Assembly) { }
public override void Configure(Funq.Container container)
{
Routes.Add<Hello>("/hello")
.Add<Hello>("/hello/{Name}");
}
}
Can anyone please tell me what namespace or DLL I need to add for IService interface?
ServiceStack's IService<T> is in the ServiceStack.ServiceHost namespace which lives in the ServiceStack.Interfaces.dll, why here's the class:
https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Interfaces/ServiceHost/IService.cs
Note: If you're just starting out, it's probably better to inherit from ServiceStack.ServiceInterface.ServiceBase<T> and override the Run() method which is a useful base class that provides things like auto exception handling for you.
If you want to be able run different code for different HTTP Verbs e.g GET/POST/PUT/DELETE (i.e. creating REST web services) than you want to inherit from RestServiceBase instead and override its OnGet/OnPost/OnPut/OnDelete methods.
I am using unity, entity framework 4 with POCO classes, repository pattern for DAL and services for Business Logic control.
I also want to use Unit of Work so I can package together CRUD operations which I perform on different services and then commit them all together.
My question is what would be the proper way to inject the Unit Of Work mechanism into my application using Microsoft Unity?
I understand that I can put the IUnitOfWork together with the repository on the constructor of the proper service and then if Unity mapping is specified it would auto initiate the proper instances, but this way I do not pass the global unit of work but rather create a new instance on each level, which can't be a smart way to do it (actually the repository is initiated even before the service).
What am I missing? (Attached is constructor code as I wrote it now of service and its repository).
U also understand that I can use Unity's ParameterOverrides method to take some global instance of Unit of Work (lets say from my aspx.cs file) and pass it into the service and then into the repository. But it seems a bit lame. Is this my only option?
Thanks
public class GenericRepository<T> : IUnitOfWorkRepository, IGenericRepository<T> where T : BaseEntity, IAggregateRoot
{
private IUnitOfWork _uow;
/// <summary>
/// Returns the active object context
/// </summary>
private ObjectContext ObjectContext
{
get
{
return ObjectContextManager.GetObjectContext();
}
}
public GenericRepository(IUnitOfWork uow)
{
_uow = uow;
}
//blahhhh...
public void Add(T entity)
{
_uow.RegisterNew(entity, this);
}
public void Delete(T entity)
{
_uow.RegisterRemoved(entity, this);
}
//.....blah blah....
public void PersistCreationOf(IAggregateRoot entity)
{
this.ObjectContext.AddObject(GetEntitySetName(), entity);
}
public void PersistUpdateOf(IAggregateRoot entity)
{
// Do nothing as EF tracks changes
}
public void PersistDeletionOf(IAggregateRoot entity)
{
this.ObjectContext.DeleteObject(entity);
}
}
public class CategoryRepository : GenericRepository<XComSolutions.FB.Domain.Model.Entities.Category>, ICategoryRepository
{
public CategoryRepository(IUnitOfWork uow)
: base(uow)
{ }
}
public class CategoryService : ICategoryService
{
public int myID {get; set;}
private ICategoryRepository _categoryRepository;
private IUnitOfWork _uow;
public CategoryService(ICategoryRepository categoryRepository,
IUnitOfWork uow)
{
_categoryRepository = categoryRepository;
_uow = uow;
}
public List<Category> GetAll()
{
return _categoryRepository.GetAll();
}
}
Define an IUnitOfWorkFactory and inject that in your services:
public class Service
{
private readonly IUnitOfWorkFactory factory;
public Service(IUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void DoOperation()
{
using (UnitOfWork context = this.factory.CreateNew())
{
this.DoSomeStuff(context);
this.DoMoreStuff(context);
context.SubmitChanges();
}
}
}
What I think you need to do is to define unit of work factory. You register this factory with your DI container and you resolve for this factory every time you need your unit of work. Then you get unit of work from the factory, work with it and let it go. You often will see that you need your unit of work within a scope of single method or single class. This article discuss Unit of Work pattern in connection with Entity Framework: http://msdn.microsoft.com/en-us/magazine/dd882510.aspx
I have a facade in a library that exposes some complex functionality through a simple interface. My question is how do I do dependency injection for the internal types used in the facade. Let's say my C# library code looks like -
public class XYZfacade:IFacade
{
[Dependency]
internal IType1 type1
{
get;
set;
}
[Dependency]
internal IType2 type2
{
get;
set;
}
public string SomeFunction()
{
return type1.someString();
}
}
internal class TypeA
{
....
}
internal class TypeB
{
....
}
And my website code is like -
IUnityContainer container = new UnityContainer();
container.RegisterType<IType1, TypeA>();
container.RegisterType<IType2, TypeB>();
container.RegisterType<IFacade, XYZFacade>();
...
...
IFacade facade = container.Resolve<IFacade>();
Here facade.SomeFunction() throws an exception because facade.type1 and facade.type2 are null. Any help is appreciated.
Injecting internal classes is not a recommended practice.
I'd create a public factory class in the assembly which the internal implementations are declared which can be used to instantiate those types:
public class FactoryClass
{
public IType1 FirstDependency
{
get
{
return new Type1();
}
}
public IType2 SecondDependency
{
get
{
return new Type2();
}
}
}
And the dependency in XYZFacade would be with the FactoryClass class:
public class XYZfacade:IFacade
{
[Dependency]
public FactoryClass Factory
{
get;
set;
}
}
If you want to make it testable create an interface for the FactoryClass.
If the container creation code is outside the assembly of the internal types, Unity can't see and create them and thus can't inject the dependecies.