Dependency Injection in MVC 1.0(ASP.NET Core)

Please note that below post would be more clear for those who already know what Dependency injection is.

As we all know that things has been little changed in .Net core and things has also been changed the way we suppose to register all of our services that we are going to use as DI.

Suppose you have one HomeController and in that controller you want to inject a service let us say MyService.

In controller it would look like as it was used to :

public HomeController(IMyServcie myService)
{

}

And in a class library called MyService, it would look like as below:

public class MyService : IMyService
{
private readonly IMyRepository _myRepository;

public MyService(IMyRepository myRepository)
{
_myRepository = myRepository;
}
…….
}

You can even inject services into views using @inject. I have already written post on that which is here.

So now you might be wondering like where should we register this.

ConfigurationServices is your composition root so that’s where you register you services.

So it would be as below:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();

// Add application services.
services.AddScoped<IMyService, MyService >();
}

Okay so above scenario is ideal scenario but you might be having some questions as below:

  • What if you have some of your code written outside of your MVC application?.
  • Also what if you do not want to bloat the ConfigurationServices method with lots of AddScoped lines of code for other layers like Repository layer and Service layer?
  • What to do if I need to do in my other layers (Repository and Service) to first register them here (both are .NET Core class library projects) and then wire those containers into the parent container?

For that you just need to create different Extension methods in different layers which targets IServiceCollection as below:

public static IServiceCollection AddMyServices(this IServiceCollection services) {
services.AddMyRepositories();
services.AddScoped<IMyService, MyService>();
//…add other services
}

And in Repository layer it would have a extension method as below:

public static IServiceCollection AddMyRepositories(this IServiceCollection services) {
services.AddScoped<IMyRepository, MyRepository>();
//…add other Repositories
}

And now you could just as easily call the AddMyRepositories() in the AddMyServies extension method as opposed to the main project itself:

public void ConfigureServices(IServiceCollection services) {
//…other code

services.AddMyServices();

//…other code
}

That is it!

Happy coding!

Advertisements

JSON with camel case in MVC

70fdb0e6-22bd-11e6-82c0-9eee1813955a

 

Yes, the wait is over.

I have heard it manytimes why MVC does not support Camel Case serialization. As workaround people used to use ServiceStack or Json.NET.

But as per recent announcement, MVC 1.0.0 now serializes JSON with camel case names by default.

How?

Before it was something like below:

public class Person
{
  public int Id { get; set; }
  public string FullName { get; set; }
}

Would serialize to:

{“Id”:1,”Name”:”Neel Bhatt”}

Now after changes, it would automatically convert it to camel case as below:

{“id”:1,”fullName”:”Neel Bhatt”} //// Not the first letter here

How to add in MVC?

Well MVC 1.0.0 gifts you this functionality  within services.AddMvc()

And in case if You want the old PascalCase behavior then you just need to add below lines into your services.AddMvc() of startup.cs class:

services

.AddMvc()

.AddJsonOptions(options =>

options.SerializerSettings.ContractResolver = new DefaultContractResolver());

Please note that it is purely configurable and if you do not wish to use this then just write above line of code in startup.cs.

Happy coding!

 

 

Moq in Asp .Net core

UPDATE on 15th October 2016:

Moq for .Net core is now available on Nuget and you can get it via below command:

nug

It means the setting mentioned below are not required now.

UPDATE on 20th October 2016:

Moq Nuget version 4.6.38-alpha worksfor .Net core- but e.g. 4.5.3 doesn’t work, that complains that Moq 4.5.3 supports net45 and one or more packages are incompatible with .NETCoreApp V1.0.

See this post for more information.

Old Post:

I was messing around a bit for Unit testing in .Net core and I suddenly remembered about mocking, and thus I decided to use Moq which is the most popular .Net mocking framework.

After few attempts I got below error while compiling:

ASP.NET Core 5.0 error CS0246: The type or namespace name ‘Moq’ could not be found (are you missing a using directive or an assembly reference?)

After searching more on this, I wondered that Moq is not supported by .Net core!!!!!

Though I thought it is not possible as Moq is very popular among developers.

After searching more, I found that ASP.NET team from Microsoft have created a special version of Moq for internal usage.

You need to add special source to your Nuget package manager to be able to locate development version of packages by .Net team.

URL of sources where you could find this packet is here

Ok, but how to use it?

There are currently several ways to use it.

First of all Register a Moq dependencies in project.json:

"dependencies": {
        "xunit": "2.2.0-beta2-build3300",
        "dotnet-test-xunit": "2.2.0-preview2-build1029",
        "moq": "4.6.38-alpha"
    }

Now for Nuget, you can perform any of below steps:

  • Configure a new NuGet feed to be able to reference the moq.netcore package
  • You can Create a NuGet.config file in project home directory.

If you have decided to create Nuget.config file then add below line of codes in that:

<?xml version="1.0" encoding="utf-8"?>
    
        
            <add key="AspNetVNext" value="https://www.myget.org/F/aspnetcidev/api/v3/index.json" />
            <add key="NuGet" value="https://api.nuget.org/v3/index.json" />
        packageSources>
configuration>

And if you have decided to configure a new Nuget feed then make sure configuration matches with below configurations:

03-armen-shimoon-aspnet-contrib

That is it!

Now you can use Moq with Asp .Net core.

Happy coding!

Blog at WordPress.com.

Up ↑