Ninject inject a service interface in a web service - asp.net

I have a web service in my project that I use to return json data to ajax calls.
Injecting my ClientService works fine on regular pages but how do I get it to work in the Web Service?
NinjectWebCommon.cs:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IClientService>().To<ClientService>();
}
Default.aspx.cs: works!
public partial class _Default : System.Web.UI.Page
{
[Inject]
public IClientService clientService { get; set; }
MyWebservice.asmx: NullReferenceException (clientService is null)
public class MyWebService: System.Web.Services.WebService
{
[Inject]
public IClientService clientService { get; set; }
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public MyObject GetClients(int id)
{
var list = clientService.GetClients(id);

I have solved this problem. I changed MyWebService class to derive from Ninject.Web.WebServiceBase:
public class MyWebService: WebServiceBase

I run on the same problem. Took me a while to figure it out.
My solution to this problem is adding statatic Ninject instantiation of Kernel in Global.asax :
public class Global : NinjectHttpApplication
{
private static Ninject.IKernel kernel = new Ninject.StandardKernel();
protected override Ninject.IKernel CreateKernel()
{
//Business TI
kernel.Bind<IYourService>().To<YourService>();
return kernel;
}
}
What enables to get it directly from singleton(public) or which solution I choosed, by accesing NinjectHttpApplication's context :
//in webservice parameterless constructor
yourService = ((NinjectHttpApplication)HttpContext.Current.ApplicationInstance).Kernel.Get<IPublicationService>();
This is the solution for working with legacy asmx web service, putting aside

Related

Controller cannot reach Controller in other project because of constructor ASP:NET Core

I'm new to ASP.NET Core and I'm trying to solve this problem for a week now.
I have a solution with two projects.
And when I start the porject the browser just says:
InvalidOperationException: Unable to resolve service for type 'TSM_Programm.Data.TSMContext' while attempting to activate 'TSM_Programm.Controllers.ResourcesController'.
The first part of the solution is my API-Layer that passes data to a user (currently via postman).
The second project is my Data Access Layer.
This Layer contains several Controllers, all of them using the same constructor, which is the following:
public TSMContext _context;
public ResourcesController(TSMContext context)
{
_context = context;
}
The TSMContext Class is the following:
namespace TSM_Programm.Data
{
public class TSMContext : DbContext
{
public TSMContext(DbContextOptions<TSMContext> options)
: base(options)
{
}
public DbSet<Resource> Resources { get; set; }
public DbSet<Parameter> Parameters { get; set; }
public DbSet<ResourceToParameter> ResourceToParameters { get; set; }
public DbSet<Reservation> Reservations { get; set; }
}
So far so god, but when I am trying to start the program the controllerof the API-Layer does not seem to be able to handle the constructor.
This is my API-Conrtoller:
namespace TSM_API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class APIController : ControllerBase //Base Class without View Support
{
//Troublemaker
public ResourcesController _resources;
public ParametersController _parameters;
public ReservationsController _reservations;
public APIController(ResourcesController resources, ParametersController parameters, ReservationsController reservations)
{
_resources = resources;
_parameters = parameters;
_reservations = reservations;
}
//Function to check if controller works
//GET: api/API
[HttpGet]
public IEnumerable<string> Get()
{
// ResourcesController controller = new ResourcesController();
return new string[] { "value1", "value2" };
}
The API-Controller was not able to use its own constructors, that's why I changed the Startup.cs.
namespace TSM_API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc().AddApplicationPart(typeof(ResourcesController).Assembly).AddControllersAsServices();
services.AddMvc().AddApplicationPart(typeof(ParametersController).Assembly).AddControllersAsServices();
services.AddMvc().AddApplicationPart(typeof(ReservationsController).Assembly).AddControllersAsServices();
services.AddMvc().AddApplicationPart(typeof(TSMContext).Assembly).AddControllersAsServices();
}
I'm simply out of ideas on how to solve the problem, since I can't add the TSMContext class a service.
Any idea how to solve it?
Thank you.
I see you have not registered your dbcontext as a dependency injection. Your issue might be due to ResourceController trying to access _context as a DI but it is not registered. To use the context as a dependency injection, register it in the startup.cs as following.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TSMContext>(options => options.UseSqlServer(Configuration.GetConnectionString("YOUR_CONNECTION_STRING")));
//If you have any services that should be used as DI, then they also must be registered as like this
services.AddScoped<Interface, Class>(); //Interface refer to the service interface while class is the actual service you will use.
}

How to add base controller in asp.net mvc 6

I search about base controller in asp.net mvc 6 however there is no any source (as far as i check).So how can i add base controller in asp.net mvc and use services on constuctor method or create new methods in base controller or any idea in order to use anything like base controller?
Any help will be appreciated.
Thanks.
You can add base controller in the following way:
public class BaseController : Controller
{
public IService Service { get; }
public BaseController(IService service)
{
Service = service;
}
}
Then, you can create your own controller and inherit BaseController instead of Controller class.
public class NewController : BaseController
{
public NewController(IService service) : base(service)
{
}
public IActionResult NewAction()
{
var result = Service.ServiceMethod();
}
}
With Microsoft.Extensions.DependencyInjection name space gives us access to the following extension method HttpContext.RequestServices.GetService
Here’s the source code of our BaseController class
public abstract class BaseController<T> : Controller where T : BaseController<T>
{
private IService service;
protected IService _service => telemetryInitializer ?? (telemetryInitializer = HttpContext.RequestServices.GetService<West.TelemetryService.ITelemetryHelper>());
}
The OrderController class extends this abstract BaseController
public class OrderController : BaseController<OrderController>
{
private readonly IOrderManager _orderManager;
public OrderController(IOrderManager orderManager)
{
_orderManager = orderManager;
}
[HttpGet]
public string Get()
{
Logger.LogInformation("Hello World!");
return "Inside the Get method of OrderController";
}
}

What is the namespace for IService interface?

I am learning ServiceStack and developing simple demo for helloworld, but could not find namespace for ISservice interface, my code as per below:
public class Hello
{
public string name { get; set; }
}
public class HelloResponse
{
public string Result { get; set; }
}
public class HelloService : **IService**<Hello>
{
public object Execute(Hello request)
{
return new HelloResponse { Result = "Hello" + request.name };
}
}
public class HelloAppHost : AppHostBase
{
public HelloAppHost() : base("Hello Web Services", typeof(HelloService).Assembly) { }
public override void Configure(Funq.Container container)
{
Routes.Add<Hello>("/hello")
.Add<Hello>("/hello/{Name}");
}
}
Can anyone please tell me what namespace or DLL I need to add for IService interface?
ServiceStack's IService<T> is in the ServiceStack.ServiceHost namespace which lives in the ServiceStack.Interfaces.dll, why here's the class:
https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Interfaces/ServiceHost/IService.cs
Note: If you're just starting out, it's probably better to inherit from ServiceStack.ServiceInterface.ServiceBase<T> and override the Run() method which is a useful base class that provides things like auto exception handling for you.
If you want to be able run different code for different HTTP Verbs e.g GET/POST/PUT/DELETE (i.e. creating REST web services) than you want to inherit from RestServiceBase instead and override its OnGet/OnPost/OnPut/OnDelete methods.

ASP.Net MVC TDD using Moq

I am trying to learn TDD/BDD using NUnit and Moq.
The design that I have been following passes a DataService class to my controller to provide access to repositories.
I would like to Mock the DataService class to allow testing of the controllers.
There are lots of examples of mocking a repository passed to the controller but I can't work out how to mock a DataService class in this
scenerio.
Could someone please explain how to implement this?
Here's a sample of the relevant code:
[Test]
public void Can_View_A_Single_Page_Of_Lists()
{
var dataService = new Mock<DataService>();
var controller = new ListsController(dataService);
...
}
namespace Services
{
public class DataService
{
private readonly IKeyedRepository<int, FavList> FavListRepository;
private readonly IUnitOfWork unitOfWork;
public FavListService FavLists { get; private set; }
public DataService(IKeyedRepository<int, FavList> FavListRepository,
IUnitOfWork unitOfWork)
{
this.FavListRepository = FavListRepository;
this.unitOfWork = unitOfWork;
FavLists = new FavListService(FavListRepository);
}
public void Commit()
{
unitOfWork.Commit();
}
}
}
namespace MyListsWebsite.Controllers
{
public class ListsController : Controller
{
private readonly DataService dataService;
public ListsController(DataService dataService)
{
this.dataService = dataService;
}
public ActionResult Index()
{
var myLists = dataService.FavLists.All().ToList();
return View(myLists);
}
}
}
Create an interface like this:
public interface DataService
{
FavListService FavLists { get; }
void Commit();
}
Make your DataService implement this interface and your controller should depend on this interface. Problem solved :)
EDIT: This line of code:
dataService.FavLists.All().ToList();
is breaking the law of demeter and will be a pain to unit test your service. Create a method like AllFavList() on your service instead of all these chain of calls, it will be easier to mock.
EDIT2: How to mock you get property
dataService.SetupGet(d => d.FavLists).Returns(your_variable);

Ninject giving NullReferenceException

I'm using asp.net MVC 2 and Ninject 2.
The setup is very simple.
Controller calls service that calls repository.
In my controller I use inject to instantiate the service classes with no problem. But the service classes don't instantiate the repositories, giving me NullReferenceException.
public class BaseController : Controller
{
[Inject]
public IRoundService roundService { get; set; }
}
This works. But then this does not...
public class BaseService
{
[Inject]
public IRoundRepository roundRepository { get; set; }
}
Giving a NullReferenceException, when I try to use the roundRepository in my RoundService class.
IList<Round> rounds = roundRepository.GetRounds( );
Module classes -
public class ServiceModule : NinjectModule
{
public override void Load( )
{
Bind<IRoundService>( ).To<RoundService>( ).InRequestScope( );
}
}
public class RepositoryModule : NinjectModule
{
public override void Load( )
{
Bind<IRoundRepository>( ).To<RoundRepository>( ).InRequestScope( );
}
}
In global.axax.cs
protected override IKernel CreateKernel( )
{
return new StandardKernel( new ServiceModule( ),
new RepositoryModule( ) );
}
Have you thought about using constructor injection?
That's how I do my dependency injection with Ninject 2 & ASP.NET MVC 2 and it works all the way down the chain from controller -> service -> repository & beyond.
It also makes sense to me to have the dependencies in the constructor for your object. It makes these dependencies highly visible and obvious to any other object that has to instantiate it. Otherwise you may end up with null reference exceptions... kinda like you have here.
HTHs,
Charles
EDIT: Showing base class injection through constructors in response to the comments.
public class BaseService
{
public IRoundRepository RoundRepo { get; private set; }
public BaseService(IRoundRepository roundRepo)
{
RoundRepo = roundRepo;
}
}
public class SquareService : BaseService
{
public ISquareRepository SquareRepo { get; private set; }
public SquareService(ISquareRepository squareRepo, IRoundRepository roundRepo)
: base(roundRepo)
{
SquareRepo = squareRepo;
}
}
This is just my way of doing things... someone else may have a different idea / opinion.

Resources