Which PreApplicationStartMethod should I use? - asp.net

I noticed that when I installed StructureMap from NuGet into my ASP.NET MVC3 project, Dave Ebbo's WebActivator package was also added as a dependency.
WebActivator provides a PreApplicationStartMethod attribute and, in the boilerplate code added at install time, it is used to initialise the IoC container and dependency resolver in it's own class, instead of doing this inside Global.asax's Application_Start method.
Given that ASP.NET 4 already has its own System.Web.PreApplicationStartMethodAttribute why was it necessary for WebActivator to supply its own version and for StructureMap to use that?
I am guessing I don't have to use WebActivator's variant?
Added code for Darin:
using System.Web;
using System.Web.Mvc;
using StructureMap;
[assembly: WebActivator.PreApplicationStartMethod(
typeof(MyMvcApp.App_Start.StructuremapMvc), "Start")]
// or
[assembly: PreApplicationStartMethod(
typeof(MyMvcApp.App_Start.StructuremapMvc), "Start")]
namespace MyMvcApp.App_Start {
public static class StructuremapMvc {
public static void Start() {
var container = (IContainer) IoC.Initialize();
DependencyResolver.SetResolver(new SmDependencyResolver(container));
}
}
}

NuGet packages for DI containers in ASP.NET MVC 3 usually prefer to use WebActivator to avoid messing with any existing code that you might have in Application_Start. Ninject uses exactly the same approach.
You can have multiple WebActivator.PreApplicationStartMethod attributes in your application and prior to .NET 4.5 a single System.Web.PreApplicationStartMethodAttribute.

Related

Blazor/Razor Class Library. Dependency Injection

I am confused on how to use a Razor Class Library that requires injected objects.
I created a new razor class library project.
There is no program.cs file and hence no WebAssemblyHostBuilder to add services to?
How do I inject dependencies into the components?
A library is simply that. It's not an application. You load the DI objects in the application project. You can write extension classes in your library as a wrapper to load all the necessary objects. builder.Services.AddServerSideBlazor() is just such an extension.
Here's an example extension method for the Weather Forecast.
public static class ServiceCollectionExtensions
{
public static void AddWeatherServices(this IServiceCollection services)
{
services.AddSingleton<WeatherForecastService>();
}
}
And use it in the application startup:
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddWeatherServices();
You inject the services into your components as normal. If you use a component in an application and the necessary services aren't loaded the page on which the component is being used will throw an error.

System.Net.Http not found in net core 2.0 class library

I have the following structure of my net core solution.
API - web api
Interfaces - class library
Implementation - class library
Models - class library
In the API startup.cs, I have registered the service like so:
services.AddHttpClient();
I have a class as such in the Implementation Project
using System.Net.Http;
public IHttpClientFactory ihttpClientFactory;
public class FooImplementation: IFoo {
public void someFooMethod(){
// here call client to fetch data from api
// process this data
}
}
I wanted to inject a IHttpClientFactory into this, however it is complaining that it cannot be found. How can I resolve this error? and Also, Is this the correct approach to pass IHttpClientFactory into this class library based on the project structure?
You do have to check the documentation of IHttpClientFactory carefully, which says,
Namespace: System.Net.Http
Assembly: Microsoft.Extensions.Http.dll
That's the hint on which NuGet package to use, so you should add a package reference to Microsoft.Extensions.Http.

StructureMap and classes that cannot accept constructor arguments

I have a ASP.NET web application (not MVC) which is actually a CMS application. I'm trying to set up StructureMap IoC framework and it's working well, but I've now hit a blocker in my understanding.
In my understanding, StructureMap enforces a pattern where all dependencies are registered in the core application assembly, so underlying assemblies do not themselves have a dependency on StructureMap.
So, say my application is My.App and it references another assembly My.Logic. My dependencies are all registered in a Container in My.App. This means that a class in My.Logic can take injected dependencies using a constructor like this:
public class Foo
{
private readonly IBar bar;
public Foo(IBar bar)
{
this.bar = bar;
}
}
But now I have a case where my class in My.Logic is a type which must be registered in the CMS, and this requires that it has an empty constructor.
So the problem is, if I can't inject using constructor parameters, and My.Logic doesn't have a dependency on My.App so I don't have access to the IoC container, is it possible to use StructureMap to handle this scenario?
If not, what alternative do I have other than create the class within the same assembly as the IoC container?
Use setter injection. See here
For<IBar>().Use<MyBar>();
Policies.FillAllPropertiesOfType<IBar>();

How to inject dependencies using Ninject In ASP.NET WebForm?

I have a fair idea of using the Repository Pattern and have been attempting to "upgrade" our current way of creating ASP .Net websites. So i do the following
Create a solution with a class project called DataAccessLayer and another class project called BusinessLogicLayer. Finally a 3rd project which is my ASP .Net website (a normal site).
I add a dbml file to the DAL and drag a table, then in my BLL i add an interface and a class which implements this interface:
My interface
namespace BLL.Interfaces
{
interface IUser
{
List<User> GetAllUsers();
}
}
In my class
namespace BLL.Services
{
public class UserService : BLL.Interfaces.IUser
{
public List<User> GetUsers()
{
throw new NotImplementedException();
}
}
}
I know the code is not fully completed, but there for illustrative purposes.
So i right click the BLL project > Manage NuGet Packages > Searched for Ninject and found a few. I was overwhelmed with the number of entries returned after after further research i am lost in how to add Ninject to a normal ASP .Net website? Specifically which addin i require? As there are many MVC and reading further i think im a little confused.
I was trying to add it to the BLL project as thats where i THINK it should go so i can register my services in there.
Could anyone guide me in what i need to so in order to use Ninject entries but im not using MVC?
Install Ninject.Web either from "Package Manager Console" or NuGet.
Version is 3.2.1 as of this writing.
OR
It will install the following 4 packages -
Sample Service Class
public interface IUserService
{
List<string> GetUsers();
}
public class UserService : IUserService
{
public List<string> GetUsers()
{
return new List<string> {"john", "eric"};
}
}
Then add binding to ~/App_Start/NinjectWebCommon.cs.
In code behind page, property inject using [Inject] attribute.
In Addition in answer by win I would advise people not to get confused by using Constructor based injection in ASP.NET Webforms as Web Forms doesn't support constructor based injection simply. In default configuration they only support Property based Injections as already demonstrated by Win.

Are controller factories neccessary when using Ninject in ASP.NET mvc 4

I am at a loss of what to do with the multitude of documentation available through google in .net as regards using Ninject with asp.net mvc 4
First of all, i want to know if Controller factories are neccessary in asp.net.
Also, is constructor injection really the only way we can do dependency injection with MVC 4 because property injection and method injection does not seem to work when i use them with my controllers
I am not an expert on Ninject but as far as i know, i am only using it to link my DataSource Interface and my EfDb Class to the rest of my application.
If you need a good book that has a Real Application built around Ninject try:
Pro ASP.NET MVC 3 Framework, Third Edition
or
Pro Asp.Net Mvc 4
There are very few lines of code i am usually concerned with
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return controllerType == null
? null
: (IController) ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
ninjectKernel.Bind<IDataSource>().To<EfDb>();
}
}
Then register your NinjectControllerFactory in Global.asax.cs with:
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
As you can see, this class use Method Injection using private void AddBindings(). This makes it very easy if you are following Test Driven Development (TDD)
See the documentation here:
https://github.com/ninject/ninject.web.mvc/wiki/Dependency-injection-for-controllers, "The only thing that has to be done is to configure the Ninject bindings for its dependencies. The controller itself will be found by Ninject even without adding a binding."
NInject will automagically set up your controller dependencies (provided it has a binding for those types).

Resources