Resolving a Dependency with ServiceStack IoC Container - dependency-injection

I have a repository that implements MongoRepository which uses generics I'm trying to register the type in the container so far this is what I got:
public override void Configure(Container container)
{
container.RegisterAutoWiredAs<UserRepository,
IUserRepository>();
//Trying to wireup the internal dependencies
container.RegisterAutoWiredType(
typeof(MongoRepository<>),
typeof(IRepository<>));
}
I tried RegisterAutoWiredAs<UserRepository> as well.
The problem is when I run the application I got the following error:
Error trying to resolve Service '{ServiceName}' or one of its
autowired dependencies
I guess because I have registered the repository without registering the mongoDB repository as a dependency.
As far as I know funq doesn't support generics, but I'm not sure if that's the same scenario with ServiceStack.
the repo has the following definition:
public class UserRepository
: MongoRepository<User>, IUserRepository
{
}
public interface IUserRepository : IRepository<User>
{
}
Edit:
This is the service definition, actually pretty basic!
public class MyService : Service {
private readonly IUserRepository _userRepository;
public MyService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public UserResponse Any(UserRequest userRequest)
{
//_userRepository.GetById(id)
}
}
DTOs:
public class UserRequest
{
public string Id { get; set; }
}
public class UserResponse
{
public User User { get; set; }
}

Funq works pretty intuitively, i.e. whatever you register you can resolve. So just make sure what you're trying to resolve, is the same thing as what you've registered.
There is no magic behavior in Funq, so this is an example of what doesn't work:
container.RegisterAutoWiredType(typeof(MongoRepository<>), typeof(IRepository<>));
If you want to be able to resolve MongoRepository<User> you need to register it, e.g:
container.RegisterAutoWiredAs<MongoRepository<User>,IUserRepository>();
Which you're then free to resolve like a normal dependency:
public class MyService : Service
{
private readonly IUserRepository _userRepository;
public MyService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
}

Related

'Autofac.Core.Activators.Reflection.DefaultConstructorFinder Error Autofac

I receive the following error while trying to inject one of my components:
No constructors on type 'Event.Function.Components.EventComponent' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'
As you can see, I am trying to inject the following components:
DependencyInjection.Initialize(builder =>
{
builder.RegisterType<DatabaseContext>().As<IDatabaseContext>()
.WithParameter("connectionString", ConfigurationManager.AppSettings["connectionString"].ToString());
builder.RegisterType<Repository>().As<IRepository>().SingleInstance().PropertiesAutowired();
builder.RegisterType<EventComponent>().As<IEventComponent>().SingleInstance().PropertiesAutowired();
builder.RegisterType<CommentComponent>().As<ICommentComponent>().SingleInstance().PropertiesAutowired();
}, functionName);
Below please find the class objects I am trying to inject.
public class DatabaseContext : DbContext, IDatabaseContext
{
public DatabaseContext(string connectionString) : base(connectionString)
{
}
}
public class Repository : IRepository
{
protected readonly IDatabaseContext Context;
public Repository(IDatabaseContext context)
{
Context = context;
}
}
public class EventComponent : IEventComponent
{
private readonly IRepository _repository;
private EventComponent(IRepository repo)
{
_repository = repo;
}
}
I am using .PropertiesAutoWired(), which gives the following definition, and according to my understanding, should know what IRepository is, since it is registered in the container.
Configure the component so that any properties whose types are registered in the container will be wired to instances of the appropriate service.
Am I doing something wrong?
Posting it here as it will hopefully help someone else, and maybe my future self.
After posting, I realized the constructor on my EventComponent is private, and it should be public.
So I changed:
public class EventComponent : IEventComponent
private readonly IRepository _repository;
private EventComponent(IRepository repo)
{
_repository = repo;
}
}
To:
public class EventComponent : IEventComponent
private readonly IRepository _repository;
public EventComponent(IRepository repo)
{
_repository = repo;
}
}

Entity framework 6 dynamic connections string using DI

I have a unit of work with the repository pattern with simple injector implemented and I need to change my connection string dynamically. Currently the connection string is taken from the web config. I need the connection string be taken from the database.
So I will have a database with the ASP.Net Identity and the connections strings (and other configurations needed for my application) and then a database depending on the client.
My repositories and Unit of work are as follows.
public abstract class DataRepositoryBase<TEntity, TContext> : IDataRepository<TEntity>
where TEntity : class, IObjectStateEntity, new()
where TContext : class, IDbSimpleContextAsync
{
protected DataRepositoryBase(TContext context)
{
Context = context;
}
public virtual TContext Context { get; }
public IEnumerable<TEntity> Get()
{
return Context.Get<TEntity>();
}
public TEntity Get(object id)
{
return Context.Find<TEntity>(id);
}
}
public class SomeRepository : DataRepositoryBase<SomeObject, IContext>, ISomeRepository
{
public SomeRepository (IContext context) : base(context)
{
}
}
public abstract class UnitOfWorkBase : IUnitOfWork
{
private IDbSimpleContextAsync _dbContext;
protected UnitOfWorkBase(IDbSimpleContextAsync dbContext)
{
_dbContext = dbContext;
}
public int SaveChanges()
{
return _dbContext.SaveChanges();
}
public Task<int> SaveChangesAsync()
{
return _dbContext.SaveChangesAsync();
}
}
public class UnitOfWork : UnitOfWorkBase, IUnitOfWork
{
private ISomeRepository _someRepository
private readonly IContext _dbContext;
public UnitOfWork(IContext dbContext) : base(dbContext)
{
_dbContext = dbContext;
}
public ISomeRepository SomeRepository => _someRepository ?? (_someRepository = new SomeRepository(_dbContext));
}
public class BookingBusiness : IBookingBusiness
{
protected IAllotmentUnitOfWork UnitOfWork { get; }
public AllotmentBusinessBase(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
...
business methods here
...
}
So my idea is when reaching business, I query the configuration database for the connection string for the current user (the current unit of work injected points to that database), and somehow use that connection to instantiate a new unit of work for to connect to the correct database. Any ideas how i can achieve this using my current setup?
You should prevent injecting objects into the object graph that change based on runtime information. The question here is whether or not the connection string is still a constant value (won't change after the application started), or can change from request to request (for instance, when each user gets its own connection string).
In case the connection string is a constant, the solution is simple: Just request the connection string at start-up and use it indefinitely, just as you already are doing currently.
If your connection string isn't a constant value from the config file, but runtime information, it and its consuming DbContext should not be injected anymore directly into the object graph. Instead, you should define an abstraction that allows requesting the correct DbContext based on runtime information, such as logged in user.
So instead of injecting an IContext into SomeRepository and UnitOfWork, inject an IContextProvider, which can be defined as follows:
public interface IContextProvider
{
IContext Context { get; }
}
Your DataRepositoryBase can use IContextProvider as follows:
public IEnumerable<TEntity> Get()
{
return this.contextProvider.Context.Get<TEntity>();
}
public TEntity Get(object id)
{
return this.contextProvider.Context.Find<TEntity>(id);
}
The part left is to define an implementation for IContextProvider that can load the right connection string from the database, and create and cache a DbContext based on that connection string. Considering the limited amount of information given, this is only something you will know how to do.

how to implement dependency injection in mvc?

I'm trying to implement dependency injection but i know how to implement the interface and repository of classes then i don't know what shall i do.
This my sample:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
This is my interface:
public interface IUser
{
IEnumerable<User> GetUsers();
void AddUser(User user);
void EditUser(User user);
void DeleteUser(int id);
User UserGetById(int id);
void Save();
}
This is my repository:
public class UserRepsitory:IUser
{
private _Context _context;
public UserRepsitory(_Context _context)
{
this._context = _context;
}
public IEnumerable<User> GetUsers()
{
return _context.User.ToList();
}
public void AddUser(User user)
{
_context.User.Add(user);
}
public void EditUser(User user)
{
_context.Entry(user).State = System.Data.Entity.EntityState.Modified;
}
public User UserGetById(int id)
{
return _context.User.Find(id);
}
public void Save()
{
_context.SaveChanges();
}
public void DeleteUser(int id)
{
var Search = _context.User.Find(id);
_context.User.Remove(Search);
}
}
And one of method in controller:
private IUser userRepsitory;
public UsersController()
{
this.userRepsitory = new UserRepsitory(new _Context());
}
public UsersController(IUser UserRepository)
{
this.userRepsitory = UserRepository;
}
public ActionResult Index()
{
return View(userRepsitory.GetUsers());
}
What is the next step?
The first thing is, get rid of the default constructor where we are hard coding the initialization of UserRepository ! We will do that in the dependency injection way.
public UsersController : Controller
{
private readonly IUser userRepsitory;
public UsersController(IUser UserRepository)
{
this.userRepsitory = UserRepository;
}
public ActionResult Index()
{
return View(userRepsitory.GetUsers());
}
}
Now we need something to tell the MVC framework which version/implementation of IUser should be used when the code runs. you can use any dependency injection frameworks to do that. For example, If you are in MVC 6, you can use the inbuilt dependency injection framework to do that. So go to your Startup class and in your ConfigureServices method, you can map an interface to a concrete implementation.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IUser, UserRepository>();
}
}
If you are in a previous version of MVC, you may consider using any of the dependency injection frameworks available like Unity, Ninject etc.
It is pretty much same, you map an interface to a concrete implementation
Ninject
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUser>().To<UserRepository>();
}
You do not need to put the mapping in a cs file. You can define that in a config file. For example, when you use Unity you can do something like this in your config file (web config or an external config file for unity configuration)
Unity
<alias alias="IUser" type="YourNamespace.IUser, YourAssemblyName" />
<register type="IUser" mapTo="YourNamespace.UseRepository, YourAssemblyName">
In order to create and configure your project with Spring DI(Dependency Feature) you must configure beans.
Create an xml file (if its not there) and add references to bean
In this xml file, provide references to the classes you want to inject. Example:
<bean id="Name of the JAVA Class" class="the Full path of the JAVA class"/>
And in your class where you are supposed to call the referencing class(above), calling procedure would be like :
#Controller
public class MyController {
private full.path.of.my.class.named.MyJavaClass _class;
#Autowired
private MyController (full.path.of.my.class.MyJavaClass class)
{
this._class= class;
}
}
Now say if you a function in MyJavaClass
public int sum(int x, int y){
return x+y;
}
Then without creating object of MyJavaClass you can inject like the following in your controller:
_class.Sum(10,15);
YOU DO NOT CREATE AN INSTANCE OF THIS CLASS.

Quartz .net does not work when I inject dependency

I am using Quartz .net v2.3.3.0 and Castle Windsor v3.3.0.0.
I have a job which is dependent on a Service
public class DemoJob : IJob
{
private readonly IService _Service;
public DemoJob(IService Service)
{
_Service = Service;
}
public void Execute(IJobExecutionContext context)
{
_Service.CallRepoMethod();
}
}
This is the service class which is in different project
public class Service: IService
{
public void CallRepoMethod()
{
Repo();
}
}
Everything works fine till now.
But as soon as I inject dependency in service class the job is not executed.
public class Service: IService
{
private readonly IRepository _repository;
Service(IRepository repository)
{
_repository = repository;
}
public void CallRepoMethod()
{
_repository.Repo();
}
}
IRepository is implemented by a simple Repository class with a single method.
Repository class is in different project and IService,Service and IRepository are in same project.
I don't get any error message but the job does not get executed. If i remove dependency from the Service class then everything works fine and jobs execute.
Here is how I have registered the dependencies
internal class CastleWindsorContainer : IContainer
{
public static WindsorContainer Container { get; private set; }
public CastleWindsorContainer()
{
Container = new WindsorContainer();
}
public void Register()
{
Container.Register(Component.For<IRepository>().ImplementedBy<Repository>().LifestyleTransient());
public Object Resolve(Type controllerType)
{
return Container.Resolve(controllerType);
}
public void Release(IController controller)
{
Container.Release(controller);
}
public void RegisterJobs(IJobFactory jobFactory)
{
Container.Register(Component.For<IJobFactory>().Instance(jobFactory).LifestyleTransient());
Container.Register(Component.For<IQuartzInitializer>().ImplementedBy<JobsConfig>().LifestyleTransient());
Container.Register(Component.For<IService>().ImplementedBy<Service>().LifestyleTransient());
Container.Register(Component.For<DemoJob>().ImplementedBy<DemoJob>().LifestyleTransient()
);
Container.Resolve<IQuartzInitializer>().RegisterJobs();
}
}
code in Global.asax
var container = new CastleWindsorContainer();
IJobFactory jobFactory = new WindsorJobFactory(container);
container.Register();
container.RegisterJobs(jobFactory);
I am not able to figure out what's wrong. I searched for the solution and found many links but it didn't help because all of them show only one level of dependency. What if the dependent class is dependent on another class?
You can find my demo project here:DemoProject
Some links I checked
Quartz .net Windsor Facility
Thank You

ASP.NET MVC 3 Application using Ninject, Entity Framework 4 Code-First CTP 5, Patterns

I've tried to build some base project with above technologies. I wanted maximum flexibility and testability so I tried to use patterns along the way to make this as a base for future projects. However, it seem
something is wrong or whatever and I really need help here. So i have two questions :
Is there anything wrong with my current code? I've applied patterns correctly? Any suggestions or recommendation that would lead me in the right direction?
Why do this code actually connect to the database, create it, but doesn't support insert even if I perform the corrects operation? (Look at the end of the post for details about this error) FIXED
I believe this could also help others since I haven't found enough information in order to make something up correctly. I am pretty sure lots of people try to do it the right way and are not sure like me if what I am doing is right.
I have two entities: Comment and Review
COMMENT
public class Comment
{
[Key]
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Author { get; set; }
public virtual string Body { get; set; }
}
REVIEW
public class Review
{
[Key]
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Author { get; set; }
public virtual string Body { get; set; }
public virtual bool Visible { get; set; }
public IEnumerable<Comment> Comments { get; set; }
}
I built up a base repository for each of them this way :
GENERIC REPOSITORY
public abstract class EFRepositoryBase<T> : IRepository<T> where T : class
{
private Database _database;
private readonly IDbSet<T> _dbset;
protected IDatabaseFactory DatabaseFactory { get; private set; }
protected Database Database { get { return _database ?? (_database = DatabaseFactory.Get()); } }
public EFRepositoryBase(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
_dbset = Database.Set<T>();
}
public virtual void Add(T entity)
{
_dbset.Add(entity);
}
public virtual void Delete(T entity)
{
_dbset.Remove(entity);
}
public virtual T GetById(long id)
{
return _dbset.Find(id);
}
public virtual IEnumerable<T> All()
{
return _dbset.ToList();
}
}
For specific operations, I use an interface:
public interface IReviewRepository : IRepository<Review> {
// Add specific review operations
IEnumerable<Review> FindByAuthor(string author);
}
So I am getting the generics operations from the abstract class plus the specific operations:
public class EFReviewRepository : EFRepositoryBase<Review>, IReviewRepository
{
public EFReviewRepository(IDatabaseFactory databaseFactory)
: base(databaseFactory)
{ }
public IEnumerable<Review> FindByAuthor(string author)
{
return base.Database.Reviews.Where(r => r.Author.StartsWith(author))
.AsEnumerable<Review>();
}
}
As you figured out, I also use a database factory will produce the database context :
DATABASE FACTORY
public class DatabaseFactory : Disposable, IDatabaseFactory
{
private Database _database;
public Database Get()
{
return _database ?? (_database = new Database(#"AppDb"));
}
protected override void DisposeCore()
{
if (_database != null)
_database.Dispose();
}
}
DISPOSABLE (Some extensions methods...)
public class Disposable : IDisposable
{
private bool isDisposed;
~Disposable()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!isDisposed && disposing)
{
DisposeCore();
}
isDisposed = true;
}
protected virtual void DisposeCore()
{
}
}
DATABASE
public class Database : DbContext
{
private IDbSet<Review> _reviews;
public IDbSet<Review> Reviews
{
get { return _reviews ?? (_reviews = DbSet<Review>()); }
}
public virtual IDbSet<T> DbSet<T>() where T : class
{
return Set<T>();
}
public Database(string connectionString)
: base(connectionString)
{
//_reviews = Reviews;
}
public virtual void Commit()
{
base.SaveChanges();
}
/*
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// TODO: Use Fluent API Here
}
*/
}
And to finish, I have my unit of work....
UNIT OF WORK
public class UnitOfWork : IUnitOfWork
{
private readonly IDatabaseFactory _databaseFactory;
private Database _database;
public UnitOfWork(IDatabaseFactory databaseFactory)
{
_databaseFactory = databaseFactory;
}
protected Database Database
{
get { return _database ?? (_database = _databaseFactory.Get()); }
}
public void Commit()
{
Database.Commit();
}
}
I also bound using Ninject the interfaces:
NINJECT CONTROLLER FACTORY
public class NinjectControllerFactory : DefaultControllerFactory
{
// A Ninject "Kernel" is the thing that can supply object instances
private IKernel kernel = new StandardKernel(new ReviewsDemoServices());
// ASP.NET MVC calls this to get the controller for each request
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return null;
return (IController)kernel.Get(controllerType);
}
private class ReviewsDemoServices : NinjectModule
{
public override void Load()
{
// Bindings...
Bind<IReviewRepository>().To<EFReviewRepository>();
Bind<IUnitOfWork>().To<UnitOfWork>();
Bind<IDatabaseFactory>().To<DatabaseFactory>();
Bind<IDisposable>().To<Disposable>();
}
}
}
However, when I call in the constructor (the default action) ...
public class ReviewController : Controller
{
private readonly IReviewRepository _reviewRepository;
private readonly IUnitOfWork _unitOfWork;
public ReviewController(IReviewRepository postRepository, IUnitOfWork unitOfWork)
{
_reviewRepository = postRepository;
_unitOfWork = unitOfWork;
}
public ActionResult Index()
{
Review r = new Review { Id = 1, Name = "Test", Visible = true, Author = "a", Body = "b" };
_reviewRepository.Add(r);
_unitOfWork.Commit();
return View(_reviewRepository.All());
}
}
This seem to create the database but doesnt't insert anything in the database in EF4. It seem that I may figured out the problem.. while looking at the database object.. the connection state is closed and server version throw an exception of this kind :
ServerVersion = '(((System.Data.Entity.DbContext (_database)).Database.Connection).ServerVersion' threw an exception of type 'System.InvalidOperationException'
I am doing the right things? Is there anything wrong in what I've built ?
Also if you have recommandation about the code I posted, I would be glad. I am just trying to the learn the right way for building any kind of application in MVC 3. I want a good a start.
I use :
Entity Framework 4 with Code-First
ASP.NET MVC 3
Ninject as DI Container
SQL Server Express (not R2)
Visual Studio 2010 Web Express
Eww. This one was sneaky. Actually i don't know ninject much so i couldnt figure it out right away.
I found the solution for the SECOND question which was related to the error by finding that ninject actually shoot two instance of the DatabaseFactory, one for the repository and one for the unit of work. Actually, the error was not the problem. It was an internal error in the object database but its normal i think since im using Entity Framework.
The real problem was that Ninject was binding two different instance of IDatabaseFactory which lead to 2 connection open.
The review was added to the first set in _reviewRepostory which was using the first instance of the Database.
When calling commit on the unit of work.. it saved nothing due to the fact that the review wasnt on this database instance. In fact, the unit of work called the databasefactory which lead to creating a new instance since ninject sent a new instance of it.
To fix it simply use :
Bind<IDatabaseFactory>().To<DatabaseFactory>().InSingletonScope();
instead of
Bind<IDatabaseFactory>().To<DatabaseFactory>();
And now all the system work correctly!
Now, would love some answers regarding the first question which was if there anything wrong with my current code ? Ive applied patterns correctly ? Any suggestions or recommendation that would lead me in the right direction ?
One small observation: by having your EFRepositoryBase and IReviewRepository have methods that return an IEnumerable<> instead of an IQueryable<>, you prevent subsequent methods from adding filter expressions/constraints or projections or so on to the query. Instead, by using IEnumerable<>, you will do any subsequent filtering (e.g. using LINQ extension methods) on the full result set, rather than allowing those operations to affect and simplify the SQL statement that gets run against the datastore.
In other words, you are doing further filtering at the webserver level, not at the database level where it really belongs if possible.
Then again, this may be intentional - sometimes using IEnumerable<> is valid if you do want to prevent callers of your function from modifying the SQL that is generated, etc.

Resources