structuremap configuration asp.net mvc 4 - asp.net-mvc-4

I have a problem with MVC4 StructureMap configuration, when I run the project the compiler fires this error
No Default Instance defined for PluginFamily Mace_CrmSystem.Controllers.HomeController
this is my code
global.aspx code
namespace Mace_CrmSystem
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteTable.Routes.MapRoute("Oqla", "Oqla", new { controller = "Home", action = "index" });
RouteConfig.RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new MyCustomeFactory());
ObjectFactory.Initialize(x => x.For<string>().Use<string>());
}
}
}
MycustomeFactory class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StructureMap;
namespace Mace_CrmSystem
{
public class MyCustomeFactory : System.Web.Mvc.DefaultControllerFactory
{
protected override System.Web.Mvc.IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return StructureMap.ObjectFactory.GetInstance(controllerType) as System.Web.Mvc.IController;
}
}
}
Controller class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mace_CrmSystem.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public HomeController(string parameter)
{
TempData["Hi"] = "Hi";
}
public ActionResult Index()
{
return View();
}
}
public class logger
{
public void log()
{
}
}
}
what I noticed that when I add a parameter of type object like
public HomeController(logger parameter)
instead of
public HomeController(string parameter)
and
ObjectFactory.Initialize(x => x.For<logger>().Use<logger>());
instead of
ObjectFactory.Initialize(x => x.For<string>().Use<string>());
it works probably but with the string parameter it does not work .
so please couold anyone explain that for me.

From my understanding of StructureMap (and someone please correct me if I'm wrong) the reason you're seeing the behaviour that you're seeing is because StructureMap will use the longest constructor by default and attempt to fill in the parameters with the default instance registered with StructureMap.
In your instance you're not providing a default instance of string so StructureMap doesn't know how to resolve it.
If you wish to do what you're trying to do then your best bet is to look at creating a custom convention (see this answer for more information), however these do rely on knowing the name of the property your constructor is expecting.
Generally though, when dealing with strings your best bet is to move the string to an intermediate type and inject that instead.

Related

abp.io + hangfire issue A suitable constructor for type XXXX could not be located

I'm just trying to run a background job with ABP.IO project and Hangfire (I have already made it with aspnetboilerplate without any issue)
Each time my recurringjob start it throw this error :
A suitable constructor for type 'AbpIo.TachePlan.ITachePlanifiee' could not be located.
For this test I just write an Interface in Contracts project
using System;
using System.Collections.Generic;
using System.Text;
namespace AbpIo.TachePlan
{
public interface ITachePlanifiee
{
void Test();
}
}
and the implementation in Application project
using System;
using System.Collections.Generic;
using System.Text;
namespace AbpIo.TachePlan
{
public class TachePlanifiee : ITachePlanifiee
{
public TachePlanifiee()
{ }
public void Test()
{
//Great job
}
}
}
In the web project
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
//default ABP.IO code
app.UseHangfireDashboard();
RecurringJob.AddOrUpdate<ITachePlanifiee>(x=> x.Test(), "*/15 * * * *");
}
but result is
System.InvalidOperationException
A suitable constructor for type 'AbpIo.TachePlan.ITachePlanifiee' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
System.InvalidOperationException: A suitable constructor for type 'AbpIo.TachePlan.ITachePlanifiee'
could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Hangfire.AspNetCore.AspNetCoreJobActivatorScope.Resolve(Type type)
at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_0.<PerformJobWithFilters>b__0()
at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter filter, PerformingContext preContext, Func`1 continuation)
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_1.<PerformJobWithFilters>b__2()
at Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext context, IEnumerable`1 filters)
at Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context, IStorageConnection connection, String jobId)
I need help because I don't understant where is my mistake
Regards
Thank you for you comments, they help me.
So I found my mistake.
My interface didn't implement one of these interface
ITransientDependency
ISingletonDependency
IScopedDependency
https://docs.abp.io/en/abp/latest/Dependency-Injection
using Volo.Abp.DependencyInjection;
namespace AbpIo.TachePlan
{
public interface ITachePlanifiee : ITransientDependency
{
void Test();
}
}

Usage of HttpContext in dotnet core 2.2

I would like get key from sessions, but the compiler is complaining that the class is static when it is not. Can anyone please help me out?
using Microsoft.AspNetCore.Mvc;
using LitOnline_V1.Models;
using Microsoft.AspNetCore.Http;
namespace Test{
public class GetValidateUer{
public int GetUserValidation(){
var isValidated = HttpContext.Session.GetInt32("isValidated");
return isValidated;
}
}
}
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'HttpContext.Session'
hope it help
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Some Code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Some Code
}

Does OData actually work in AspNetCore on Linux?

I work in an environment where all new work is done in AspNetCore, one of the primary reasons being so we can run it on Linux servers. We have an API to access one of our databases that I've been asked to add OData to. No problem.
The Problem
I've got a lovely example working in a test project and I'm moving it over to the real API in a branch of the code annnnnnd.....what's that? It's a reference to Microsoft.AspNet.
My test project is .NetCore 2.1, and the only NuGet packages installed are:
Microsoft.AspNetCore.App v2.1.1
Microsoft.AspNetCore.OData v7.0.1 (tried v7.1.0 too)
Microsoft.AspNetCore.Razor.Design v2.1.2
Microsoft.NETCore.App v2.1.0
This (truncated) code works great on my Windows development machine, but I foresee problems when we try to build it for Linux deployment.
Startup.cs - Notice the first 2 usings
using Microsoft.AspNet.OData.Builder;
using Microsoft.AspNet.OData.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.OData.Edm;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ODataTest.Models;
namespace ODataTest
{
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddOData();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseMvc(b =>
{
b.Filter().Expand();
b.MapODataServiceRoute("odata", "odata", GetEdmModel());
b.EnableDependencyInjection();
});
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<ThingDto>(nameof(ThingDto));
return builder.GetEdmModel();
}
}
}
ThingController.cs - Notice using #3
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.OData;
using Microsoft.AspNetCore.Mvc;
using ODataTest.Models;
namespace ODataTest.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ODataController
{
private readonly Db _db;
public ValuesController(Db db)
{
this._db = db;
}
[HttpGet]
[EnableQuery]
public ActionResult<IEnumerable<ProductPricePointMarkdownDto>> Index()
{
var things =
from thing in _db.Things
select new ThingDto
{
ThingID = thing.ID,
StyleID = thing.StyleID,
ColourID = thing.ColourID
};
return Ok(things);
}
}
}
ThingDto.cs - Notice the last using
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.OData.Query;
namespace ODataTest.Models
{
[Filter("ColourID", Disabled = true)]
[Filter]
public class ThingDto
{
[Key]
public int ThingID { get; set; }
public int StyleID { get; set; }
public int ColourID { get; set; }
}
}
Can anyone steer me away from my current thinking that OData "works with Core" is marketing, and in reality it doesn't?
So the answer is "Yes, it does work". I have not tracked down whether it's a bad namespace, or actually referring to .NET Standard. The motivation to find out went once I proved this ran on a Linux docker container.

How to add web API to an existing MVC Hottowel project

I have one Hottowel project created using it's template from Visual Studio. I want to add the Web API feature in that project. I have created a Web Api controller to the controller folder and tries to access like "http://localhost:53397/api/Values" But I get an error saying The resource cannot be found error.
My controller code looks like below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MvcApplication8.Controllers
{
public class ValuesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
I have the cs file in APP_start folder called BreezeWebApiConfig.cs which contains the logic to map the route like below.
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "BreezeApi",
routeTemplate: "api/{controller}/{action}"
);
Let me know If I am missing any configuration setting for Web APi.
Try to decorate your ApiController like bellow :
[BreezeController]
public class NorthwindIBModelController : System.Web.Http.ApiController {
readonly EFContextProvider<NorthwindIBContext> ContextProvider =
new EFContextProvider<NorthwindIBContext>();
[HttpGet]
public String Metadata() {
return ContextProvider.Metadata();
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle) {
return ContextProvider.SaveChanges(saveBundle);
}
[HttpGet]
public IQueryable<Customer> Customers() {
return ContextProvider.Context.Customers;
}
For more information have a look to breeze documentation here.
Its seems like you are making a wrong Url Request. Look at your breeze route configuration for WebApi. You need to Pass like that http://localhost:53397/api/Values/Get as breeze is using Controller action based routing.
Hope this will help.

NinjectServiceHost in WCF service does not call Dispose()

I've been trying to get the Dispose method on my IDisposable WCF service called whilst using Ninject's NinjectServiceHost without any luck. I've then downloaded the Ninject.extensions.WCF example code and tried to get the IDisposable TimeService's Dispose() method to be called, but it does not get called either.
The service is instantiated correctly, just the Dispose() doesn't get called.
Is this a bug or something that myself and the example code are missing?
I've created a stripped down service and testing host that reproduces the issue. The code is below.
I'm using Ninject 3.0.1.10, Ninject.extensions.WCF 3.0.0.5, .net 4.5
ServiceModule.cs code (for setting up bindings)
using Ninject.Modules;
namespace TestNinjectWcf
{
public class ServiceModule : NinjectModule
{
public override void Load()
{
Bind<Service1>().ToSelf();
// I've also tried Bind<IService1>().To<Service1>()
// and also tried various scopes such as InParent() and InRequestScope()
}
}
}
Console Test Program to start the service.
using System;
using Ninject.Extensions.Wcf;
using Ninject;
using TestNinjectWcf;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel(new ServiceModule());
var service = kernel.Get<NinjectServiceHost<Service1>>();
service.Open();
Console.WriteLine("Service Started");
Console.ReadKey();
service.Close();
}
}
}
Service Implementation
using System;
using System.Diagnostics;
using System.ServiceModel;
namespace TestNinjectWcf
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service1 : IService1, IDisposable
{
public Service1()
{
Debug.WriteLine("Constructor");
}
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public void Dispose()
{
Debug.WriteLine("Dispose"); // This line never gets called!
}
}
}
Maybe it is that you have created singleton service ? (InstanceContextMode.Single)
Only one InstanceContext object is used for all incoming calls and is not recycled subsequent to the calls. If a service object does not exist, one is created