I'm trying to set the variable DB as global and use anywhere.
My problem is that I'm initialising twice the db. In the base controller and in atributes.
ie:
public class SettingsAttribute : ActionFilterAttribute {
public ApplicationDbContext db = new ApplicationDbContext();
public override void OnActionExecuting(ActionExecutingContext filterContext) {
...
}
and
[Settings]
public class BaseController : Controller {
public ApplicationDbContext db = new ApplicationDbContext();
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state) {
...
}
I would like to create the var db just once, and access anywhere in the project.
How ca I do this?
Consider using of Dependency Injection pattern. For .NET there is for example Unity container, which implements a lightweight, extensible dependency injection container. Check the List of dependency injection containers for .NET, but it's quite old.
In general, Dependency injection is called Inversion of Control (IoC). That means, your classes, which are using for example your DB class, don't need to be dependent on a specific DB class. Instead, they just require a specific interface. DB class implementing this interface is injected from the outside and your class is decoupled from a specific implementation of DB class.
Some places to start with:
Dependency Injection on Wikipedia.org
Why does one use dependency injection?
An Absolute Beginner's Tutorial on Dependency Inversion Principle, Inversion of Control and Dependency Injection
Dependency Injection in Windows Communication Foundation
What about putting it in another class (an Helper, for instance), and access it like this:
private ApplicationDbContext db = null;
public ApplicationDbContext Db {
get {
if (db == null)
db = new ApplicationDbContext();
return db;
}
}
Best practice in this situation and (similar situations) is to implement a DI/IoC pattern , as #Dawid-Ferenczy mentioned in his answer. if you never worked with it before , it's a little abstract at the beginning but it's very useful in the long run , especially if your objects got complicated. You can search online for articles to learn more about the pattern itself.
#Dawid-Ferenczy mentioned the Unity container, but it's not limited to that , you can use any container you would like (Or even create your own if you need to ).
I personally use Ninject as it has a has a lot of support documentation and i found it easy to implement.
In your case (DB context) i would use Ninject and DI/IoC as follow:
1- Declare an interface for your DB Context DAL:
public interface IModelDBContext
{
//Your methods should go here
}
Your concrete class:
public class ModelDBContext : DbContext,IModelDBContext
{
//Your methods and other stuff here
}
Container part
(Ninject in my case , but you can use any other container)
public class NinjectDependencyResolver : IDependencyResolver
{
//Bunch of initialization and methods
Check out this : [Using ninject in MVC][2].
//Binding piece (Very important)
private void AddBindings()
{
//Context DB Binding
kernel.Bind<IModelDBContext>().To<ModelDBContext>();
//Other binding
}
}
Implementation part:
This is the fun and exciting part. anywhere in your application , if you need to implement your specific DB context you inject it with the constructor and it will be available for you to use:
In your case it will be something like this:
Public YourConcreteClass
{
Private IModelDBContext ModelDB; //Initiate an instance that you will use .
//DI by constructor
public YourConcreteClass(IModelDBContext mDB)
{
ModelDB=mDB;
}
//in the rest of your code you call ModelDB that has access to all of the methods and attributes you might need
}
Related
I'm confused about the proper way to manage my DbContext lifetime using dependency injection in my WinForms application. Right now, I have code that looks like the following
static class Program
{
// This is the main window's controller, which stores all the
// dependencies that are resolved in the composition root and handles
// passing those dependencies to other objects
private static IMainController mainController;
private static void ComposeDependencies
{
UnityContainer container = new UnityContainer();
container.RegisterType<IMyContext, MyContext>();
container.RegisterType<IOrderRepository, OrderRepository>();
container.RegisterType<IOrderService, OrderService>();
mainController = new MainController(
container.Resolve<IOrderService>());
}
}
public class OrderRepository : IOrderRepository
{
private readonly IMyContext context;
public OrderRepository(IMyContext context)
{
this.context = context;
}
}
public class OrderService : IOrderService
{
private readonly IOrderRepository repository;
public OrderService(IOrderRepository repository)
{
this.repository = repository;
}
}
public class MainController
{
private readonly IOrderService orderService;
public MainController(IOrderService orderService)
{
this.orderService = orderService;
}
public void DoSomethingWithAnOrder()
{
FirstTypeOfController controller = new FirstTypeOfController(this.orderService);
// Show window, assign controller, etc.
}
public void DoSomethingElseWithAnOrder()
{
SecondTypeOfController controller = new SecondTypeOfController(this.orderService);
// Show window, assign controller, etc.
}
}
The problem I'm having is that this pattern results in all of my repositories getting created when my program starts, so the MyContext instances stay around through the whole program. So when the database gets updated outside of my program, my program doesn't see the new data because MyContext is using references to the data that it already has loaded.
If this were a web application, then I'd have new dependencies made with every request, but since this is WinForms, I don't understand how to get around this problem while keeping a single composition root and without passing my Unity container all around my program (or having a static reference to it) so that each controller can resolve its own per instance dependencies.
What's the standard solution to this problem, and is there something that I'm doing incorrectly with how/where I'm composing my dependencies or using my DbContext?
I know that MVC is meant more for web applications and something like MVVM or MVP is perhaps more suited to non-web, but those would both have this same problem with a single composition root that only gets called once.
It depends on how you configured your dependency injection, if its Singleton or one instance per scope. I know that on Ninject's DI framework you can specify by using:
//Thread Scope (New instance on each injection)
kernel.Bind<IInterface>.To<ConcreteClass>().InThreadScope();
//Singleton Scope (One instance per application)
kernel.Bind<IInterface>.To<ConcreteClass>().InSingletonScope()
I dont see anything wrong with your implementation, it looks correct. That is right, you are initializing your repositories when your program starts, and that is good, and you keep your contexts for the entire application lifespan. With repositories, you call a method that performs some action against database; in case of fetching data, you always will get the latest data, no matter what, if implemented correctly, unless you would retrieve it on application load and store it somewhere for future access (like global variables, settings as an example).
I'm currently working on a WinForms system (I know) where there's a lot of Constructor Injection when creating forms, but if those forms/views need to open another form, I find the DI container has been injected too so that we can locate the implementation of the desired view interface at runtime. e.g.
public partial class MyView : Form, IMyView
{
private readonly IDIContainer _container;
public MyView(IDIContainer container)
{
InitializeComponent();
_container = container;
}
public OpenDialogClick(object sender, EventArgs e)
{
var dialog = container.Resolve<IDialogView>();
dialog.ShowDialog(this);
}
}
I'm aware that this is basically using the container as a service locator. I've been repeatedly told that this is considered an anti-pattern so I'd like to avoid this usage.
I could probably inject the view as part of the constructor like this :
public partial class MyView : Form, IMyView
{
private readonly IDialogView _dialog;
public MyView(IDialogView dialog)
{
InitializeComponent();
_dialog = dialog;
}
public OpenDialogClick(object sender, EventArgs e)
{
dialog.ShowDialog(this);
}
}
But what if the dialog view is quite expensive to instantiate?
It's been suggested that we create some kind of form factory which internally uses the DI container, but to me this seems like simply creating a wrapper around another service locator.
I know that at some point, something has to know how to create an IDialogView, so I'm thinking that either it's resolved when the composite root is created (probably not ideal if there are many forms and some or all are expensive to create), or the composite root itself has a way to resolve the dependency. In which case the composite root has to have a service-locator-like dependency? But then how would child forms create dialogs like this? Would they call up to the composite via, say, events, to open dialogs like this?
One particular problem I keep running up against is that the container is almost impossible to mock easily. This is partly what keeps me thinking about the form factory idea, even though it would just be a wrapper around the container. Is that a sensible reason?
Have I thought myself into a knot? Is there a simple way through this? Or do I just cut the knot and find something that works for me?
Or do I just cut the knot and find something that works for me?
Factory class:
public interface IDialogFactory {
IDialogView CreateNew();
}
// Implementation
sealed class DialogFactory: IDialogFactory {
public IDialogView CreateNew() {
return new DialogImpl();
}
}
// or singleton...
sealed class SingleDialogFactory: IDialogFactory {
private IDialogView dialog;
public IDialogView CreateNew() {
if (dialog == null) {
dialog = new DialogImpl();
}
return dialog;
}
}
Your code:
public partial class MyView : Form, IMyView {
private readonly IDialogFactory factory;
public MyView(IDialogFactory factory) {
InitializeComponent();
//assert(factory != null);
this.factory = factory;
}
public OpenDialogClick(object sender, EventArgs e) {
using (var dialog = this.factory.CreateNew()) {
dialog.ShowDialog(this);
}
}
}
Registration with SimpleInjector
container.RegisterSingle<IDialogFactory, DialogFactory>();
or using singleton version
container.RegisterSingle<IDialogFactory, SingleDialogFactory>();
container.RegisterSingle<IMyView, MyView>();
A local factory, satisfied with an implementation that uses the container and set up in the composition root is not a service locator, it is a dependency resolver.
The difference is as follows: the locator is defined and satisfied somewhere near the definition of the container. In a separate project, to use the locator, you need an external reference to the container infrastructure. This causes the project to rely on external dependency (the locator).
On the other hand, the dependency resolver is local to the project. It is used to satisfy dependencies in its close neighbourhood but it doesn't depend on anything external.
The composition root should not be used to resolve actual specific dependencies such as the one you are concerned about. Instead, the compositon root should set up implementations of all these local dependency resolvers that are used throughout the application. The more local resolver, the better - the MVC's constructor factory is a good example. On the other hand, WebAPI's resolver handles quite few of different services and it is still a good resolver - it is local in the webapi infrastructure, it doesn't depend on anything (rather - other webapi services depend on it) and it can be implemented in any possible way and set up in the Composition Root.
Some time ago I wrote a blog entry about it
http://www.wiktorzychla.com/2012/12/di-factories-and-composition-root.html
There you will find your issue discussed and an example of how you set up a factory aka resolver.
You definitely do not want to pass your DI container around your application. Your DI container should only be part of your Composition Root. You could, however, have a factory that uses the DI container within the Composition Root. So if Program.cs is where you are wiring everything up, you could simply define that factory class there.
WinForms was not designed with DI in mind; forms are generated and therefore need default constructors. This may or may not be an issue depending on which DI container you use.
I think in this case, the pain of using constructor injection in WinForms is greater than the pain of any pitfalls you may encounter while using a service locator. There's no shame in declaring a static method in your Composition Root (Program.cs) that wraps a call to your DI container to resolve your references.
I know this problem very well. Everything I learned about solution to this (and I learned A LOT) is more or less camouflaging service locator.
I am sure there are answers on here to my question, though I just don't either quite understand what I'm looking for or what I'm reading... Also, not 100% sure DI is what I should be using in this case.
I am attempting to use Unity for my DI. I am injecting dependency into ASP.Net Web API Controllers. And so far so good.
I am injecting Services into my controllers that the controller will require. For example, in one of my controllers I have:
private TransactionService _transactionService;
public TransactionsController(TransactionService transactionService)
{
_transactionService = transactionService;
}
In this case I am injecting an instance of TransactionService into the controller. This is all working.
My WebApiConfig.cs contains the following, which as i understand it actually performs the injection:
var container = new UnityContainer();
container.RegisterType<ServiceBase>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
I can show you my UnityResolver if needed.
Now the part I'm struggling with...
My services all inherit from an Abstract class ServiceBase - in its simplest for it looks like this:
public abstract class ServiceBase : IDisposable
{
internal Account _account;
public ServiceBase(){}
}
What I would like to do is create the Account during my injection process and pass it in somehow so that my injected services don't need to deal with instansiating the account.
The moment I try adding any constructors to my services to accept an Account I receive the message to ensure my controllers have a parameterless constructor.
So.. how do i set up my DI so that I can inject services into my controllers and also inject a pre-instantiated instance of Account into my services?
Update
I forgot to mention (sorry Wiktor) - I would like to NOT use Attributes if possible. It seems strange in my mind that we can use DI to unhook dependency and then go and put a bunch of dependent attributes everywhere. I quite possibly just don't understand the DI concept correctly, though this doesn't seem right to me
That should be simple, just make the additional property public and add the dependency attribute on it.
[Dependency]
public Account _account { get; set; }
Unity should be able to inject the attribute and you can even register the Account class in an ordinary way (for example with an injection factory).
I hope this would give some idea for you.
Create an interface for service base and declare Acccount as public property.
Interface for your service:
you can also inherit other interfaces.
public interface ITransactionService : IDisposable
{
IAccount Account{get;set;}
}
Implement it in your class:
public class TransactionService : ITransactionService{
private IAccount _account;
public IAccount Account
{
get
{if(_account==null)_account=new Account(); return _account;}
set
{_account=value;}
}
}
Now use the constructor at API controller as shown below:
private ITransactionService _transactionService;
public TransactionsController(ITransactionService transactionService)
{
_transactionService = transactionService;
}
Unity resolver:
var container = new UnityContainer();
container.RegisterType<ITransactionService,TransactionService>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
So using in this way where property injection and constructor injection used for reducing tightly coupled dependency.
It will be very easy for mocking the interface for unit testing.
You may also create an interface for Account class, so that it could be easy for mocking based on your use.
In case you don't want to use attributes, which I totally agree with, the best approach is to have ServiceBase accept the account parameter, like:
public abstract class ServiceBase {
private Account _account;
public ServiceBase(Account account) {
this._account = account;
}
}
You will have to declare the same constructor on your derived service as well TransactionService. When the controller is instantiated, Unity will correctly create the instance of Account class first and then pass it on to your TransactionService object via constructor injection. And you should register Account object using a life time manager to scope it to singleton.
Hope this helps.
I have a layered application with the following projects:
DAL (using EntityFramework with repositories)
DAL.Model (contains the entities, and is referenced by all the others)
Services
UI (in wpf)
The base repository looks like this:
public abstract class RepositoryBase<T> where T : class
{
private readonly MyContext context;
private readonly IDbSet<T> dbSet;
protected RepositoryBase(MyContext dataContext)
{
context = dataContext;
dbSet = context.Set<T>();
}
protected MyContext Context
{
get { return context; }
}
**And a series of virtual methods for Add, Delete, etc.
}
All repositories extend this one, such as:
public class MarketRepository : RepositoryBase<Market>
{
public MarketRepository(MyContext dataContext) : base(dataContext)
{
}
public IEnumerable<Market> GetAllMarkets()
{
return this.Context.Markets.ToList<Market>();
}
}
The services look like this:
public class MarketService
{
IMarketRepository _marketRepository;
public MarketService(IMarketRepository marketRepository)
{
_marketRepository = marketRepository;
}
public IEnumerable<Market> GetAllMarkets()
{
return _marketRepository.GetAllMarkets();
}
}
What I would like to achieve is that the UI layer would only have a reference to the Services layer, the Services layer only with the DAL layer (and all of them to Model, where the entities live) using DI (right now I'm using Unity).
The problem is, in my container in the UI I only want to do this
unity.RegisterType<IMarketService, MarketService>();
and not have to do it as well for the repositories, because then the UI layer would have a dependency on the DAL layer.
I thought about adding a parameterless constructor to the Service classes, like:
public MarketService() : this(new MarketRepository(*What would I put here?)) { }
but then I'm loosing the abstraction that the interface gives, and also I don't know what to do with the MyContext that the repository needs as a parameter; if I pass a new one, then I need to reference the DAL.
Should I change my repositories to create a new MyContext in the constructor, rather than getting it as a parameter?
How can I refactor my architecture to make it work properly and with minimal dependencies?
Well, I belive it is up to the bootstrapper to configure dependencies, in the higher level of the application. As it is usually the UI project, if it needs to reference other assemblies, so be it. If you do not like your UI project managing that, than create a bootstrapper project responsable for getting your app running and separete your UI classes in another one.
Your IoC container should support Dependency Injection using a string from an external configuration file. This way you are not hardcoding the mapping. Structuremap does this quite well, so I am sure other IoCs will.
Adding external dependenices as a parameter when creating an instance is the way to go.
I think you should make yourself more familiar with the different ways to configure Unity, so that the dependencies are resolved.
Could you elaborate why you are creating a repository when using a dependency injection framework?
When configuring DI, you should follow the same pattern - UI bootstrapper initializes Services, Services initialize DAL. (With autofac or ninject you could achiece this using modules. With unity you should emulate modules).
In pseudocode something like
//ui
void UILayer.ConfigureUnity(unity)
{
ServiceLayer.ConfigureUnity(unity)
}
//services
void ServiceLayer.ConfigureUnity(unity)
{
DAL.ConfigureUnity(unity)
unity.RegisterType<IMarketService, MarketService>();
}
//dal
void DAL.ConfigureUnity(unity)
{
unity.RegisterType<IMarketRepository, MarketRespository>();
unity.RegisterType<MyContext, MyContext>(); //not sure exact syntax - just register type for 'new Type()' activator.
}
I apologise for the length, and I know there are some answers on this but I searched a lot and haven't found the right solution,
so please bear with me.
I am trying to create a framework for legacy applications to use DI in ASP.NET webforms. I will probably use Castle Windsor
as the framework.
These legacy applications will use in part an MVP pattern in some places.
A presenter would look something like this:
class Presenter1
{
public Presenter1(IView1 view,
IRepository<User> userRepository)
{
}
}
Now the ASP.NET Page would look something like this:
public partial class MyPage1 : System.Web.UI.Page, IView1
{
private Presenter1 _presenter;
}
Before using DI I would instantiate the Presenter as follows in the OnInit of the page:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
_presenter = new Presenter1(this, new UserRepository(new SqlDataContext()));
}
So now I want to use DI.
First I must create a handler factory to override the construction of my page.
I found THIS really good answer to help:
How to use Dependency Injection with ASP.NET Web Forms
Now I can easily set up my containers in my composition root as Mark Seeman suggest to use the Global.asax
(This means though to create a static container that must be thread safe and sealed not to be able to add further registrations)
Now I can go and declare the constructor injection on the page
public MyPage1() : base()
{
}
public MyPage1(Presenter1 presenter) : this()
{
this._presenter = presenter;
}
Now we run into the first problem, I have a circular dependency.
Presenter1 depends on IView1, But the page depends on the presenter.
I know what some will say now that the design is probably incorrect when you have circular dependencies.
First I dont think the Presenter design is incorrect, by it taking a dependency in the constructor to the View, and I can say this
by looking at plenty of MVP implementations.
Some may suggest changing the Page to a design where Presenter1 becomes a property and then using Property injection
public partial class MyPage1 : System.Web.UI.Page, IView1
{
[Dependency]
public Presenter1 Presenter
{
get; set;
}
}
Some may even suggest removing the dependency to presenter completely and then simply Wiring up via a bunch of events, But this is
not the design I wanted and frankly dont see why I need to make this change to accomodate it.
Anyway regardless of the suggestion, another problem exists:
When the Handler factory gets a page request only a type is available (NOT THE VIEW INTERFACE):
Type pageType = page.GetType().BaseType;
now using this type you can resolve the Page via IoC and its dependencies:
container.Resolve(pageType)
This will then know that there is a property called Presenter1 and be able to inject it.
But Presenter1 needs IView1, but we never resolved IView1 through the container, so the container won't know
to provide the concrete instance the handler factory just created as it was created outside of container.
So we need to hack our handler factory and replace the view interface:
So where the handler factory resolves the page:
private void InjectDependencies(object page)
{
Type pageType = page.GetType().BaseType;
// hack
foreach (var intf in pageType.GetInterfaces())
{
if (typeof(IView).IsAssignableFrom(intf))
{
_container.Bind(intf, () => page);
}
}
// injectDependencies to page...
}
This poses another problem, most containers like Castle Windsor will not allow you to reregister this interface
to the instance it is pointing to now. Also with the container being registered in the Global.asax, it is not thread-safe to
do as the container should be read only at this point.
The other solution is to create a function to rebuild the container on each web request, and then check to see
if the container contains the component IView if not set the instance. But this seems wasteful and goes against suggested use.
The other solution is to create a special Factory called
IPresenterFactory and put the dependency in the page constructor:
public MyPage1(IPresenter1Factory factory) : this()
{
this._presenter = factory.Create(this);
}
The problem is that you now need to create a factory for each presenter and then make a call to the container
to resolve other dependencies:
class Presenter1Factory : IPresenter1Factory
{
public Presenter1Factory(Container container)
{
this._container = container;
}
public Presenter1 Create(IView1 view)
{
return new Presenter1(view, _container.Resolve<IUserRepository>,...)
}
}
This design also seems cumbersome and over complicated, does any one have ideas for a more elegant solution?
Perhaps I misunderstand your problems, but the solution seems fairly simple to me: promote the IView to a property on the Presenter1:
class Presenter1
{
public Presenter1(IRepository<User> userRepository)
{
}
public IView1 View { get; set; }
}
This way you can set the presenter on the view like this:
public Presenter1 Presenter { get; set; }
public MyPage1()
{
ObjectFactory.BuildUp(this);
this.Presenter.View = this;
}
Or without property injection, you can do it as follows:
private Presenter1 _presenter;
public MyPage1()
{
this._presenter = ObjectFactory.Resolve<Presenter1>();
this._presenter.View = this;
}
Constructor injection in Page classes and user controls will never really work. You can get it to work in full trust (as this article shows), but it will fail in partial trust. So you will have to call the container for this.
All DI containers are thread-safe, as long as you don't manually add registrations yourself after the initialization phase and with some containers even that is thread-safe (some containers even forbid registering types after initialization). There would never be a need to do this (except for unregistered type resolution, which most containers support). With Castle however, you need to register all concrete types upfront, which means it needs to know about your Presenter1, before you resolve it. Either register this, change this behavior, or move to a container that allows resolving concrete types by default.