Practical example of using Castle.Windsor with MVVMLight Toolkit - mvvm-light

I have really tried but I cannot find a good working example of using the Castle IOC with MVVMLight. Any sort of guidance in the way to dynamically generate ViewModelBase viewmodels would be appreciated. I am trying to use Constructor Injection to associate the viewmodel with a data source, something like:
public class MainViewModel : ViewModelBase
{
...
public MainViewModel( ISomeSortofDataRepsoitory mysomesortofdata)
myrepo = mysomesortofdata; /// data items in an observable collection
}
and I want the ViewModelLocator to do something like:
public static void CreateMain()
{
if (_main == null)
{
...
_main = ioc.Resolve<MainViewModel>();
...
}
}
alas, no dice. Any working examples?

You need to install the CommonServiceLocator.WindsorAdapter package from NuGet. Then in your ViewModelLocator ctor
var container = new WindsorContainer();
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
OR
Delete the ViewModelLocator class altogether, and put all your Castle Windsor configuration in
override void OnStartup(StartupEventArgs e)
in App.xaml.cs

Related

EntityFramework dependency injection of DatabaseContext on Asp.Net

i have not much knowledge about Asp and Entity Framework so i really cant figure out what i have to do.
My problem is accessing database context out of main asp method -
There is how db context created and used in Program.cs (Main)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<DatabaseContext>(
options => options.UseSqlite(builder.Configuration.GetConnectionString("DefaultDataSource"))
);
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var context = services.GetRequiredService<DatabaseContext>();
context.Database.EnsureCreated();
}
so my problem is kinda that i making "options" for DatabaseContext constructor out of "builder.Configuration"
But what do i do when i need to acces db from other script? DatabaseContext requires config but i just dont know how to get it outside of that builder.
one guy suggested me to use Dependency Injection, i have looked but i just cant get how to do it properly, like i make a class where i initialize db context, but i still need to somehow make a config here and i really have no clue how.
It could be really stupid question but i really cant figure it out for a couple of days :D
I`ve tried to make DbContext without a config but it gives error
I don't know what you tried, but I think this might be what you want.
Assuming your DatabaseContext class is the most basic, and defines a table
Users in it:
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
public DbSet<Models.User> Users { get; set; }
}
Then you register it in Program.cs:
builder.Services.AddDbContext<DatabaseContext>(
options => options.UseSqlite(builder.Configuration.GetConnectionString("DefaultDataSource"))
);
You can generate your database by migrating and updating the database(Of course you can also manually create):
Add-Migration InitialCreate
Update-Database
Then you can access your database in other classes through dependency injection, such as in the controller:
public class HomeController : Controller
{
private readonly DatabaseContext _databaseContext;
public HomeController(DatabaseContext databaseContext)
{
_databaseContext = databaseContext;
}
public IActionResult Index()
{
var user = _databaseContext.Users.ToList();
return View();
}
}
For more details about dependency injection, you can refer to this document.

How do you inject a view dependency into Presenter (MVP) in ASP.NET Web Forms using Simple Injector or Microsoft.Extensions.Dependency?

The following example shows a scenario where I'm trying to implement a DI container. In this case, I'm trying to use Simple Injector or Microsoft.Extensions.DependencyInjection DI Container. I've seen code examples that start hitting around the target, such as here, but no bullseye as of yet.
Below is a general code sample that I would like to modify to use one of the aforementioned DI containers (Used Simple Injector for example). I could move the view out of the presenter constructor and set it as a property. However, I was hoping for a more eloquent solution also it is a dependency that needs to be injected.
I know .NET 4.7.2 has increased DI support functionality but the biggest benefit seems to be allowing dependencies to be easily injected into pages/user controls. For MVP architecture I need the concrete class of the page tied to its view interface so the DI container can resolve and pass into the presenter, as the presenter depends on the view. I've not seen an example of this implemented well other than Unity using its DependencyOverride, which can pass the concrete class at runtime.
public partial class UserLoginView : IUserLoginView
{
private UserLoginPresenter _userLoginPresenter;
protected override void OnLoad(EventArgs e)
{
//This is my problem:
//An error will be thrown "...contains the parameter with name
//'view' and type IUserLoginView, but IUserLoginView is not
//registered..."
_userLoginPresenter = SimpleInjectorDependencyInjector
.GetInstance<IDeveloperTestStatusPresenter>();
}
}
public class UserLoginPresenter : IUserLoginPresenter
{
private readonly IUserLoginView view;
private readonly IUserService _userService;
public UserLoginPresenter(IUserLoginView userLoginView,
IUserService userService)
{
this.view = userLoginView;
this._userService = userService;
}
public static class SimpleInjectorDependencyInjector
{
private static readonly Container container = new Container();
public static T GetInstance<T>() where T : class
{
return container.GetInstance<T>();
}
//Assume this is called from App on start
public static void RegisterClasses()
{
container
.Register<IUserLoginPresenter, UserLoginPresenter>();
container
.Register<IUserService, UserService>();
}
}
I was able to accomplish what I was looking for using Microsoft.Extensions.DependencyInjection Container.
In my MSDependencyInjector wrapper class, I used the ActivatorUtilities extension.
public static T GetService<T, I>(I interfaceInstance)
{
return ActivatorUtilities.CreateInstance<T>(container, interfaceInstance);
}
Implemented in my page's partial class I wrote:
_userLoginPresenter = MSDependencyInjector.GetService<UserLoginPresenter,
IUserLoginView>(this);
A Caveat: The 'T' parameter of createInstance wants the concrete class type not the interface. This caused hours of frustration, prompting the creation of this question in the first place. MS documentation isn't the greatest but I definitely misread.
I'm not sure how to implement something as straightforward in Simple Injector and would be interested in knowing. Based on my reading I not sure if my solution isn't something like a service locator, which depending on which camp you are from should be avoided. However, if the implementation of this can be contained for just solving the need for this MVP paradigm then it is my hope all will be well.

Repository pattern with mvc without entity framework

Is repository pattern with unit of work best fit for entity framework application?
I am creating a new asp.net mvc application and i want to use stored procedure (microsoft enterprise library) instead of Entity framework(or any other ORM).
So how can i use repository pattern with mvc application?
I have explored many tutorials but not getting expected result. Please suggest me better approach for n tier application.
You have to understand that "repository pattern" is just an idea to organize your code. I think you can still use it without any problem.
I just want to provide you an example of implementation using sql stored procedure: suppose you have to manage the classic table "Contacts".
You can create your UnitOfWork contract:
public interface IContactsRepository {
void AddContact(Contact c);
void RemoveContact(Contact c);
void UpdateContact(Contact c);
void Search(string keyword);
}
After, you can create your own implementation without using EF:
public sealed class SPContactsRepository : IContactsRepository {
// Is just an exampl.e
public void AddContact(Contact c) {
var sqlCommnad = new SqlCommand(this._connectionString);
sqlCommand.CommandText = "dbo.AddContact";
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.AddParameter("Name", c.Name);
sqlCommand.Connection.Open();
sqlCommand.ExecuteNonQuery();
}
}
Hope this can help!
So just to continue what Roberto already started, your controller in the MVC app will look like this:
public class ContactsController : Controller
{
private readonly IContactsRepository _contactsRepo;
public ContactsController(IContactsRepository repo)
{
_contactsRepo = repo;
}
}
These pattern uses dependency injection(DI). There are several options for DI container. You can use Unity which is a Microsoft package that you can install via nuget package manager to your MVC web project. The install will create a UnityConfig.cs file in your App_Start folder. You can register the dependency as:
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<IContactsRepository, SPContactsRepository>();
}
And in your Global.asax.cs file inside Application_Start(), you initialize the container:
UnityConfig.RegisterComponents();
If you use EF, the DbContext is already your Unit of Work and the DbSet as your repository. Having said that, you should not create a repository that will add another layer of data abstraction. Instead, you can create, domain services.

Applying Dependency Injection on an ASP.NET web forms application built using MVP Pattern

I am creating an ASP.NET Web forms application with MVP pattern. The structure of my view is something like this:
public partial class ShipperView : System.Web.UI.Page, IShipperView
{
ShipperPresenter presenter;
public ShipperOperationsView()
{
IShipperOperations operations = new ShipperOperations();
INavigator navigator = new Navigator();
presenter = new ShipperPresenter(this,operations,navigator); //Instantiating presenter
}
...
}
The basic structure of my presenter is something like this:
public class ShipperPresenter
{
IShipper shipperView;
IShipperOperations operations;
INavigator navigator;
public ShipperPresenter(IShipperView view,IShipperOperations operations,INavigator navigator)
{
shipperView = view;
this.operations = operations;
this.navigator = navigator;
}
...
}
I don't want to instantiate my presenter using the new keyword, I would like to replace it with resolving dependency. During the dependency resolution, I want to pass the instance of the present view to the dependency resolver. I tried searching a lot on this but did not get any satisfactory answer.
Can this issue be resolved using any of the IoC containers like StructureMap, Ninject, Unity or MEF? Any pointer would be of great help.
To solve this problem you could use property injection.
First, register ShipperOperations, Navigator and ShipperPresenter in the DI container.
Then, in the Page_Load method of your view, invoke the resolve method of the DI container of your choice.
public class ShipperPresenter
{
IShipper shipperView;
IShipperOperations operations;
INavigator navigator;
public ShipperPresenter(IShipperOperations operations,INavigator navigator)
{
this.operations = operations;
this.navigator = navigator;
}
public IShipper ShipperView
{
get { return shipperView; }
set { shipperView = value; }
}
...
}
And the view would look like this:
public partial class ShipperView : System.Web.UI.Page, IShipperView
{
ShipperPresenter presenter;
protected void Page_Load(object sender, EventArgs e)
{
presenter = YourIOC.Resolve<ShipperPresenter>();
presenter.ShipperView = this;
}
...
}
You could also use a factory to create the presenter at runtime, while passing it the parameters of your choice. In fact, in a DI world, this is THE way to proceed when you want to instantiate objects with dependencies that are only known at runtime. There is a nice mechanism for this in Castle Windsor, it's called typed factories.
Using a factory, no need to modify the presenter class. Instead, create an interface for the factory:
public interface IShipperPresenterFactory
{
ShipperPresenter Create(IShipper shipperView);
}
If using Windsor, the only thing that you have to do is to register this interface as a typed factory. With other DI containers, you will have to implement a class that uses the DI container internally to resolve the presenter.
The Page_Load method of the view would then use the factory like this:
protected void Page_Load(object sender, EventArgs e)
{
var factory = YourIOC.Resolve<IShipperPresenterFactory>();
presenter = factory.Create(this);
}

How to use Dependency Injection with ASP.NET Web Forms

I am trying to work out a way to use dependency injection with ASP.NET Web Forms controls.
I have got lots of controls that create repositories directly, and use those to access and bind to data etc.
I am looking for a pattern where I can pass repositories to the controls externally (IoC), so my controls remain unaware of how repositories are constructed and where they come from etc.
I would prefer not to have a dependency on the IoC container from my controls, therefore I just want to be able to construct the controls with constructor or property injection.
(And just to complicate things, these controls are being constructed and placed on the page by a CMS at runtime!)
Any thoughts?
UPDATE 2019:
With the introduction of Web Forms 4.7.2, there is now better support for DI. This invalidates the below. See: Wiring up Simple Injector in WebForms in .NET 4.7.2
You can use automatic constructor injection by replacing the default PageHandlerFactory with a custom one. This way you can use an overloaded constructor to load the dependencies. Your page might look like this:
public partial class HomePage : System.Web.UI.Page
{
private readonly IDependency dependency;
public HomePage(IDependency dependency)
{
this.dependency = dependency;
}
// Do note this protected ctor. You need it for this to work.
protected HomePage () { }
}
Configuring that custom PageHandlerFactory can be done in the web.config as follows:
<?xml version="1.0"?>
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.aspx"
type="YourApp.CustomPageHandlerFactory, YourApp"/>
</httpHandlers>
</system.web>
</configuration>
Your CustomPageHandlerFactory can look like this:
public class CustomPageHandlerFactory : PageHandlerFactory
{
private static object GetInstance(Type type)
{
// TODO: Get instance using your favorite DI library.
// for instance using the Common Service Locator:
return Microsoft.Practices.ServiceLocation
.ServiceLocator.Current.GetInstance(type);
}
public override IHttpHandler GetHandler(HttpContext cxt,
string type, string vPath, string path)
{
var page = base.GetHandler(cxt, type, vPath, path);
if (page != null)
{
// Magic happens here ;-)
InjectDependencies(page);
}
return page;
}
private static void InjectDependencies(object page)
{
Type pageType = page.GetType().BaseType;
var ctor = GetInjectableCtor(pageType);
if (ctor != null)
{
object[] arguments = (
from parameter in ctor.GetParameters()
select GetInstance(parameter.ParameterType)
.ToArray();
ctor.Invoke(page, arguments);
}
}
private static ConstructorInfo GetInjectableCtor(
Type type)
{
var overloadedPublicConstructors = (
from constructor in type.GetConstructors()
where constructor.GetParameters().Length > 0
select constructor).ToArray();
if (overloadedPublicConstructors.Length == 0)
{
return null;
}
if (overloadedPublicConstructors.Length == 1)
{
return overloadedPublicConstructors[0];
}
throw new Exception(string.Format(
"The type {0} has multiple public " +
"ctors and can't be initialized.", type));
}
}
Downside is that this only works when running your side in Full Trust. You can read more about it here. But do note that developing ASP.NET applications in partial trust seems a lost cause.
Starting from .NET 4.7.2 (what's new), it is now easy for developers to use Dependency Injection in WebForms applications. With the UnityAdapter, you can add it to your existing WebForms application in 4 simple steps. See this blog.
Autofac supports fairly unobtrusive dependency injection in ASP.NET WebForms. My understanding is it just hooks into the ASP.NET page lifecycle using an http module and does property injection. The only catch is that for controls I don't think this happens until after the Init event.
The best way is to have a base class for the controls like:
public class PartialView : UserControl
{
protected override void OnInit(System.EventArgs e)
{
ObjectFactory.BuildUp(this);
base.OnInit(e);
}
}
That will inject any control that inherits from that base class (uses structuremap). Combining that with a property based config, you will be able to have controls like:
public partial class AdminHeader : PartialView
{
IMyRepository Repository{get;set;}
}
Update 1: If you can't have the controls inherit, perhaps the CMS has a hook right after creating the controls, in there you can call the BuildUp. Also if the CMS allows you to hook something to fetch the instance you could use constructor based injection, but I prefer BuildUp on this specific scenario as asp.net doesn't have a hook for this.
You could also create some singleton instances in the Application_Start global.asax event and have them available as public static readonly properties.
This is a solution I recently used to avoid hooking into the pipeline (I find that confuses everyone that looks at my code in the future, but yes, I see its benefits as well):
public static class TemplateControlExtensions
{
static readonly PerRequestObjectManager perRequestObjectManager = new PerRequestObjectManager();
private static WIIIPDataContext GetDataContext(this TemplateControl templateControl)
{
var dataContext = (WIIIPDataContext) perRequestObjectManager.GetValue("DataContext");
if (dataContext == null)
{
dataContext = new WIIIPDataContext();
perRequestObjectManager.SetValue("DataContext", dataContext);
}
return dataContext;
}
public static IMailer GetMailer(this TemplateControl templateControl)
{
return (IMailer)IoC.Container.Resolve(typeof(IMailer));
}
public static T Query<T>(this TemplateControl templateControl, Query<T> query)
{
query.DataContext = GetDataContext(templateControl);
return query.GetQuery();
}
public static void ExecuteCommand(this TemplateControl templateControl, Command command)
{
command.DataContext = GetDataContext(templateControl);
command.Execute();
}
private class PerRequestObjectManager
{
public object GetValue(string key)
{
if (HttpContext.Current != null && HttpContext.Current.Items.Contains(key))
return HttpContext.Current.Items[key];
else
return null;
}
public void SetValue(string key, object newValue)
{
if (HttpContext.Current != null)
HttpContext.Current.Items[key] = newValue;
}
}
}
This shows how you can create your own life time manager pretty easily as well as hook into an IoC container if you so desire. Oh, and I am also using a query/command structure which is sort of unrelated, but more on the reasoning behind that can be found here:
Limit your abstractions: Refactoring toward reduced abstractions

Resources