NSwag Not Recognizing Custom Authorization Attributes - asp.net-core-webapi

Currently having a problem with NSwag generation on a custom authorize attribute. I have been completely unable to find anything on this issue elsewhere.
I've created a custom attribute for my WebAPI and more or less followed the patterns recommended here
internal class AuthorizeWithPermissionAttribute : AuthorizeAttribute
{
const string POLICY_PREFIX = "HasPermission";
public AuthorizeWithPermissionAttribute(string permission) { // logic excluded for brevity }
public string Permission
{
get { // code }
set { // code }
}
}
Then I decorate my controller with this attribute like so
[AuthorizeWithPermission("MY_PERMISSION_NAME")]
public class MyController: ControllerBase
{
// Controller logic.
}
So far I have tried
Creating a public parameterless constructor on the attribute
Changing the type (enum, int, string) of the constructor param
Applying [OpenApiIgnore] to the type and then writing a custom filter in Startup.cs when that didn't work
Changing the access modifier at the class and property level
Applying the attribute broadly to the controller and methods directly.
Here is the error I'm getting:
Executing file 'nswag.json' with variables 'Configuration=Debug'...
3> Launcher directory: %UserDirectory%\.nuget\packages\nswag.msbuild\13.8.2\tools\NetCore31
3> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
3> ---> System.NullReferenceException: Object reference not set to an instance of an object.
3> at %SLNNAME%.Authorization.Attributes.AuthorizeWithPermissionAttribute..ctor(String permission) in %SLNDirectory%\Authorization\Attributes\AuthorizeWithPermissionAttribute.cs:line 14
3> at System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, RuntimeType type, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs)
3> at System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, RuntimeType type, IRuntimeMethodInfo ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs)
3> at System.Reflection.CustomAttribute.AddCustomAttributes(ListBuilder`1& attributes, RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, ListBuilder`1 derivedAttributes)
3> at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType)
3> at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
3> at System.RuntimeType.GetCustomAttributes(Boolean inherit)
3> at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.CreateControllerModel(TypeInfo typeInfo)
3> at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.OnProvidersExecuting(ApplicationModelProviderContext context)
3> at Microsoft.AspNetCore.Mvc.ApplicationModels.ApplicationModelFactory.CreateApplicationModel(IEnumerable`1 controllerTypes)
3> at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors()
3> at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context)
3> at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection()
3> at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize()
3> at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.get_ActionDescriptors()
3> at Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescriptionGroupCollectionProvider.get_ApiDescriptionGroups()
3> at NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGenerator.GenerateAsync(Object serviceProvider)
3> at NSwag.AspNetCore.OpenApiDocumentProvider.GenerateAsync(String documentName)
3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.GenerateDocumentWithDocumentProviderAsync(IServiceProvider serviceProvider) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 287
3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.GenerateDocumentAsync(AssemblyLoader assemblyLoader, IServiceProvider serviceProvider, String currentWorkingDirectory) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 276
3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint.<>c__DisplayClass0_0.<<Process>b__0>d.MoveNext() in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs:line 30
3> --- End of stack trace from previous location where exception was thrown ---
3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint.Process(String commandContent, String outputFile, String applicationName) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs:line 29
3> --- End of inner exception stack trace ---
3> at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
3> at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
3> at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
3> at NSwag.AspNetCore.Launcher.Program.Main(String[] args) in C:\projects\nswag\src\NSwag.AspNetCore.Launcher\Program.cs:line 170
3> System.InvalidOperationException: Swagger generation failed with non-zero exit code '1'.
3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 221
3> at NSwag.Commands.NSwagDocumentBase.GenerateSwaggerDocumentAsync() in C:\projects\nswag\src\NSwag.Commands\NSwagDocumentBase.cs:line 280
3> at NSwag.Commands.NSwagDocument.ExecuteAsync() in C:\projects\nswag\src\NSwag.Commands\NSwagDocument.cs:line 81
3> at NSwag.Commands.Document.ExecuteDocumentCommand.ExecuteDocumentAsync(IConsoleHost host, String filePath) in C:\projects\nswag\src\NSwag.Commands\Commands\Document\ExecuteDocumentCommand.cs:line 86
3> at NSwag.Commands.Document.ExecuteDocumentCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\Document\ExecuteDocumentCommand.cs:line 32
3> at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input)
3> at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input)
3> at NConsole.CommandLineProcessor.Process(String[] args, Object input)
3> at NSwag.Commands.NSwagCommandProcessor.Process(String[] args) in C:\projects\nswag\src\NSwag.Commands\NSwagCommandProcessor.cs:line 56
3> %SLNDirectory%.csproj(59,5): error MSB3073: The command "dotnet "%UserDirectory%\.nuget\packages\nswag.msbuild\13.8.2\build\../tools/NetCore31/dotnet-nswag.dll" run nswag.json /variables:Configuration=Debug" exited with code -1.
3> Done executing task "Exec" -- FAILED.

LOGIC! LOGIC IN The constructor was the issue. Here this works. Hopefully someone won't spend two hours of their life on this like I did
public class AuthorizeWithPermissionAttribute : AuthorizeAttribute
{
const string POLICY_PREFIX = "HasPermission";
public AuthorizeWithPermissionAttribute(string permission)
{
this.Permission = permission;
}
public string Permission { get => Policy; set => Policy = $"{POLICY_PREFIX}{value}"; }
}

Related

Exception has been thrown by the target of an invocation in asp.net core and postgresql migration

I am trying to create a project. That's why I downloaded a startup template from this link. Then I tried to configure with asp.net core. I set the connection string as "Default": "User ID=postgres;Password=**********;Host=localhost;Port=5432;Database=LibraryManagementDb;Pooling=true;". and then changed UseSqlServer to UseNpgsql in LibraryManagementDbContextConfigurer class.
`
public static void
Configure(DbContextOptionsBuilder<LibraryManagementDbContext>
builder, string connectionString)
{
builder.UseNpgsql(connectionString);
}
public static void
Configure(DbContextOptionsBuilder<LibraryManagementDbContext>
builder, DbConnection connection)
{
builder.UseNpgsql(connection);
}
`
and add the below code to DbContext class
`
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(p => p.Value)
.HasMaxLength(100); // any integer that is smaller than 10485760
}
`
and removed all migration classes from the Migration folder and run add-migration Initial_Migration command in the package manager console
but I got the Exception has been thrown by the target of an invocation. error
this is the whole exception
`
PM> add-migration Initial_Migration
Build started...
Build succeeded.
System.Reflection.TargetInvocationException: Exception has been
thrown by the target of an invocation.
---> System.TypeLoadException: Method 'get_Info' in type
'Microsoft.EntityFrameworkCore.Infrastructure.
Internal.NpgsqlOptionsExt
ension' from assembly 'Npgsql.EntityFrameworkCore.PostgreSQL,
Version=2.1.0.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7'
does not have an implementation.
at Microsoft.EntityFrameworkCore
.NpgsqlDbContextOptionsExtensions.UseNpgsql[TContext]
at LibraryManagement.EntityFrameworkCore
.LibraryManagementDbContextConfigurer
.Configure(DbContextOptionsBuilder`1 builder, String
connectionString) in D:\6.0.0\aspnet-
core\src\LibraryManagement.EntityFrameworkCore
\EntityFrameworkCore\LibraryManagementDbContextConfigurer.cs:line
10
at LibraryManagement.EntityFrameworkCore
.LibraryManagementDbContextFactory.CreateDbContext(String[] args)
in D:\6.0.0\aspnet-core\src\LibraryManagement.EntityFrameworkCore
\EntityFrameworkCore\LibraryManagementDbContextFactory.cs:line 17
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor, Boolean
wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,
BindingFlags invokeAttr, Binder binder, Object[] parameters,
CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[]
parameters)
at Microsoft.EntityFrameworkCore.Design
.Internal.DbContextOperations.CreateContextFromFactory(Type
factory,
Type contextType)
at
Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.
<>c__DisplayClass16_0.<FindContextFactory>b__1()
at Microsoft.EntityFrameworkCore.Design.Internal
.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal
.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal
.MigrationsOperations.AddMigration(String name, String outputDir,
String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.AddMigrationImpl(String name, String outputDir, String
contextType,
String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.OperationBase.Execute(Action action)
Exception has been thrown by the target of an invocation.
`
How can I resolve this??? Please help...
By updating 'Npgsql.EntityFrameworkCore.PostgreSQL' solved this problem

Asp.net Core Odata on Mongodb like filter

I have a Asp.net Core 2.2 Odata Controller where I need to filter the name of persons with the "like" functionality. This errors out. Is this query support by MongoDB driver (ver 2.8.1) ?
http://192.168.1.151:5000/v2/odata/users?$filter=contains(Name, 'Smith')&$top=1&$count=true
If I I use exact or eq filter it works
http://192.168.1.151:5000/v2/odata/users?$filter=Name eq 'Smith Alan')&$top=1&$count=true
[10:30:17.208 ERR][0HLO4RQ58RQQ9:00000001] Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: An unhandled exception has occurred while executing the request.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: IIF((({document}{name} == null) OrElse False), null, Convert({document}{name}.Contains("Loi"), Nullable`1)) is not supported.
at MongoDB.Driver.Linq.Translators.PredicateTranslator.GetFieldExpression(Expression expression)
at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression)
at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node)
at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateWhere(WhereExpression node)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateOrderBy(OrderByExpression node)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateTake(TakeExpression node)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateTake(TakeExpression node)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslatePipeline(PipelineExpression node)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.Translate(Expression node, IBsonSerializerRegistry serializerRegistry, ExpressionTranslationOptions translationOptions)
at MongoDB.Driver.Linq.MongoQueryProviderImpl`1.Execute(Expression expression)
at MongoDB.Driver.Linq.MongoQueryableImpl`2.GetEnumerator()
at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
at Microsoft.AspNet.OData.Query.TruncatedCollection`1..ctor(IQueryable`1 source, Int32 pageSize)
at Microsoft.AspNet.OData.Query.ODataQueryOptions.LimitResults[T](IQueryable`1 queryable, Int32 limit, Boolean& resultsLimited)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNet.OData.Query.ODataQueryOptions.LimitResults(IQueryable queryable, Int32 limit, Boolean& resultsLimited)
at Microsoft.AspNet.OData.Query.ODataQueryOptions.ApplyTo(IQueryable query, ODataQuerySettings querySettings)
at Microsoft.AspNet.OData.EnableQueryAttribute.ExecuteQuery(Object responseValue, IQueryable singleResultCollection, IWebApiActionDescriptor actionDescriptor, Func`2 modelFunction, IWebApiRequestMessage request, Func`2 createQueryOptionFunction)
The fix for the problem is to add HandleNullPropagation to false.
[EnableQuery( HandleNullPropagation = HandleNullPropagationOption.False)]
public IActionResult Get()
{
return Ok(_db.MyMongoDataCollection().AsQueryable());
}

MoqRT Error - Unhandled Exception while Creating MoqRT.Baked.dll

I am using VS2013 community edition, SQLite and created Test project using MSTestFramework where I am referring MoqRT framework for creating mock objects.
But while creating mock objects I am getting an Error as follows,
Unhandled baking exception: --> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.DllNotFoundException: Unable to load DLL 'sqlite3': This operation is only valid in the context of an application container. (Exception from HRESULT: 0x8007109A)
at SQLite.SQLite3.Open(String filename, IntPtr& db)
at SQLite.SQLiteConnection..ctor(String databasePath)
at MoqRT.Baking.BakingController.GetDatabase()
at MoqRT.Baking.BakingController..ctor(String testAssembly, String appxPath, String bakingPath)
at MoqRT.MoqRTRuntime.InitializeBaking(String testAssembly, String appxPath, String bakingPath)
--- End of inner exception stack trace ---
Server stack trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at MoqRT.Baking.BakingWorkItem.Run(BakingContext context) in d:\Kierron Matte\Projects\Mercury\R & D\Unit Testing\MoqRT-master\MoqRT.Baker\Controller\BakingWorkItem.cs:line 35
at MoqRT.Baking.BakingPoke.RunWorkItem(BakingController owner, WorkItem item) in d:\Kierron Matte\Projects\Mercury\R & D\Unit Testing\MoqRT-master\MoqRT.Baker\Controller\BakingPoke.cs:line 36
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at MoqRT.Baking.IBakingPoke.RunWorkItem(BakingController owner, WorkItem item)
at MoqRT.Baking.BakingRunner.ThreadEntryPoint() in d:\Kierron Matte\Projects\Mercury\R & D\Unit Testing\MoqRT-master\MoqRT.Baker\Controller\BakingRunner.cs:line 55
I had referred the project and steps from GitHub "/mbrit/moqrt"
but not able to create MoqRT.Baked.dll.
I have referred the following files in my test project,
MoqRT.MetroStyle.dll
MoqRT.MetroStyle.pdb
MoqRT.MetroStyle.pri
I have also added the image for your reference.
Thanks in advance.
Unhandled Exception while Creating MoqRT.Baked.dll
I have resolved this issue by removing additional SQLite (For Windows RunTime) reference from my Test Project which was not similar as used by MoqRT version (SQLite3.dll).

No parameterless constructor object defined

I know that this is a duplicate question but i can't find answer to my error.
I'm trying to show a list of my rooms saved in database but i get next error:
Server Error in '/' Application.
No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67
[InvalidOperationException: An error occurred when trying to create a controller of type 'HotelProjectFinal.Controllers.RoomController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969412
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
But i have a constructor withou a parameter:
namespace HotelProjectFinal.Controllers
{
public class RoomController : Controller
{
private IRoomRepository repository;
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
public ViewResult List()
{
return View(repository.Rooms);
}
}
}
My view is :
#model IEnumerable<HotelProjectFinal.Models.Room>
#{
ViewBag.Title = "List";
}
#foreach (var p in Model)
{
<div class="item">
<h3>#p.Room_number</h3>
#p.Room_Type
<h4>#p.Room_Type.Price.ToString("c")</h4>
</div>
}
I am using ninject:
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<IRoomRepository>().To<EFRoomRepository>();
}
}
}
You've got a controller factory, but the fact that the stacktrace says nothing about Ninject suggests you have forgotten to tell MVC about it.
You could fix that by adding a line to tell it that.
However the recommended practice is to hook Ninject in by adding a NuGet reference to Ninject.MVC3. There are docs about it on the associated Ninject MVC3 wiki.
Please try changing your constructors to the following:
public RoomController() { } // You were missing this parameterless constructor
[Inject]
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
Ninject is looking for a parameterless constructor because you haven't specified [Inject] above constructor that you wish to use for dependency injection. This has confused "Ninject" and caused an exception to be thrown.
The primary DI pattern is Constructor Injection. When activating an instance of a type Ninject will choose one of the type’s constructors to use by applying the following rules in order:-
If a constructor has an [Inject] attribute, it is used (but if you apply the attribute to more than one, Ninject will throw a NotSupportedException at runtime upon detection).
If no constructors have an [Inject] attribute, Ninject will select the one with the most parameters that Ninject understands how to resolve.
If no constructors are defined, Ninject will select the default parameterless constructor (assuming there is one).
More information can be found here:
https://github.com/ninject/ninject/wiki/Injection-Patterns
As pointed out by Ruben, [Inject] attribute pollutes the controller with external concerns.
This ties your code to a specific container. (Although Ninject does permits the customization of the specific attribute to look for, the point remains – you’re polluting an interface with external concerns.)
Your actual problem probably relies in a missing reference to Ninject.MVC3
Even though IRoomRepository could be null, that doesn't make it a parameterless constructor. At first glace, it looks like your IoC isn't wired up correctly for IRoomRepository. With no IoC, or misconfigured IoC, the controller activator looks for a parameterless constructor for your controllers.
// This is a parameterless constructor.
public RoomController()
{ }
// This is not a parameterless constructor.
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
Edit, Are you using Ninject.Mvc and your base MvcHttpApplication is implementing NinjectHttpApplication?

Circular reference in web service

I'm trying to resolve a circular reference in a web service. The solution builds fine and some operations are callable, but one which uses a referenced type gives a circular reference exception (below).
System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: A circular reference was detected while serializing an object of type MyCoreAssembly.MyType <-------- this is the referenced type
at System.Xml.Serialization.XmlSerializationWriter.WriteStartElement(String name, String ns, Object o, Boolean writePrefixed, XmlSerializerNamespaces xmlns)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write21_VRD(String n, String ns, VRD o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write21_VRD(String n, String ns, VRD o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write31_Hereditament(String n, String ns, Hereditament o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write32_HereditamentVrd(String n, String ns, HereditamentVrd o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write33_VRDResponse(String n, String ns, VRDResponse o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write43_VRDResponse(Object o)
at Microsoft.Xml.Serialization.GeneratedAssembly.VRDResponseSerializer.Serialize(Object objectToSerialize, XmlSerializationWriter writer) <------- this is my type
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue)
at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)
at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)
at System.Web.Services.Protocols.WebServiceHandler.Invoke()
The architecture looks roughly like this:
Core layer <------ Data Layer <----- Logic Layer <---------- Web service
\/--------------------\/ <-------------------|
\/--------------------|
Each layer is a separate assembly and the web service references all three assemblies. I've attached a debugger but it doesn't break. It looks like the internals are failing but I have no idea where as everything builds. How would I go about debugging this?
Your circular reference is not in the project files, but in the objects you try to send over the webservice. One of you object has a reference to itself or an object that references to the object.
The error message tell you to look in your type: MyCoreAssembly.MyType

Resources