So, I have dug for quite some time to find the answer for this with no luck.
What am I doing wrong?
Ninject throws an exception with this message:
Error activating IModelRepository{User}
No matching bindings are available, and the type is not self-bindable.
Here's my code:
I have a generic Interface:
public interface IModelRepository<T> where T: IModel
{
//interface stuff here
}
The concrete class is:
public UserRepository : IModelRepository<User>
{
public UserRepository(IDocumentStore documentStore, string databaseName)
{
//constructor code here
}
}
Ninject module Load():
public override void Load()
{
string databaseName = Properties.Settings.Default.DefaultDatabaseName;
Bind<IModelRepository<User>>()
.To<UserRepository>()
.WithConstructorArgument("documentStore", Kernel.Get<IDocumentStore>())
.WithConstructorArgument("databaseName", databaseName);
}
Ninject instantiation (this is where the exception occurs):
Kernel = new Ninject.StandardKernel(new DIModules.ModelRepositoryModule()
,new DIModules.DocumentStoreModule());
Here's the full stack trace:
at Ninject.KernelBase.Resolve(IRequest request) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 359
at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 263
at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 37
at xl.view.DIModules.DataStoreModule.Load() in c:\Users\Michael\Google Drive\Projects\Windows\xl\xl.view\DIModules\DataStoreModule.cs:line 18
at Ninject.Modules.NinjectModule.OnLoad(IKernel kernel) in c:\Projects\Ninject\ninject\src\Ninject\Modules\NinjectModule.cs:line 85
at Ninject.KernelBase.Load(IEnumerable`1 m) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 217
at Ninject.KernelBase..ctor(IComponentContainer components, INinjectSettings settings, INinjectModule[] modules) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 100
at Ninject.KernelBase..ctor(INinjectModule[] modules) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 57
at Ninject.StandardKernel..ctor(INinjectModule[] modules) in c:\Projects\Ninject\ninject\src\Ninject\StandardKernel.cs:line 46
at xl.view.Program.InitializeApplication() in c:\Projects\Windows\xl\xl.view\Program.cs:line 53
at xl.view.Program.Main() in c:\Windows\xl\xl.view\Program.cs:line 28
.WithConstructorArgument("documentStore", Kernel.Get<IDocumentStore>())
You might want to change that to ctx=> Kernel.Get<IDocumentStore>(). The way you're calling it, you're creating objects during the module Load() - this should not be the casse - Moduel Load() methods should only Bind() stuff.
Also, don't have a dev env to hand but pretty sure there should be a way to let default provisioning take care of binding that ctor param to whatever DI would resolve.
(If none of the above makes sense, you'll definitely need to give a more complete stacktrace than you have)
Try to change order of modules, seems order is important, because IModelRepository<User> does not know about IModel and User before you bind them:
Kernel = new Ninject.StandardKernel(
new DIModules.DocumentStoreModule(),
new DIModules.ModelRepositoryModule());
This works well for me, and here is full sample: http://pastebin.com/2TjBqAwc
Related
I have a WebAPI service using SimpleInjector. I have this set up using AsyncScopedLifestyle for my scoped dependencies, and one of these dependencies is my Entity Framework DataContext. Many things in my service depend on the DataContext, and it is generally injected in to my MediatR handlers using constructor injection - this works well. Separately I have a few areas where I need to create an instance of an object given its type (as a string), so I have created a custom activator class (ResolvingActivator) that is configured with a reference to Container.GetInstance(Type):
In my container bootstrap code:
ResolvingActivator.Configure(container.GetInstance);
I can then create objects by using methods such as:
ResolvingActivator.CreateInstance<T>(typeName)
When I'm using WebAPI, the above is working perfectly.
A further part of the project is a legacy API that uses WCF. I have implemented this as a translation layer, where I translate old message formats to new message formats and then dispatch the messages to the Mediator; I then translate the responses (in new format) back to old format and return those to the caller. Because I need access to the Mediator in my WCF services, I'm injecting this in their constructors, and using the SimpleInjector.Integration.Wcf package to let SimpleInjector's supplied SimpleInjectorServiceHostFactory build instances of the services. I've also created a hybrid lifestyle, so I can use the same container for my both my WebAPI and WCF services:
container.Options.DefaultScopedLifestyle = Lifestyle.CreateHybrid(
new AsyncScopedLifestyle(),
new WcfOperationLifestyle());
This works well for some calls, but when a call ultimately calls my ResolvingActivator class, I get an ActivationException thrown, with the following message:
The DataContext is registered as 'Hybrid Async Scoped / WCF Operation' lifestyle, but the instance is requested outside the context of an active (Hybrid Async Scoped / WCF Operation) scope.
As I only receive this error when making WCF calls, I'm wondering if I have something wrong in my configuration. In a nutshell, this will work:
public class SomeClass
{
private readonly DataContext db;
public SomeClass(DataContext db)
{
this.db = db;
}
public bool SomeMethod() => this.db.Table.Any();
}
But this will not:
public class SomeClass
{
public bool SomeMethod()
{
// Code behind is calling container.GetInstance(typeof(DataContext))
var db = ResolvingActivator.CreateInstance<DataContext>();
return db.Table.Any();
}
}
Any ideas where I'm going wrong?
Edit: here is the stack trace from the ActivationException:
at SimpleInjector.Scope.GetScopelessInstance[TImplementation](ScopedRegistration`1 registration)
at SimpleInjector.Scope.GetInstance[TImplementation](ScopedRegistration`1 registration, Scope scope)
at SimpleInjector.Advanced.Internal.LazyScopedRegistration`1.GetInstance(Scope scope)
at lambda_method(Closure )
at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.Container.GetInstance(Type serviceType)
at Service.Core.ResolvingActivator.CreateInstance(Type type) in Service.Core\ResolvingActivator.cs:line 43
at Service.Core.ResolvingActivator.CreateInstance(String typeName) in Service.Core\ResolvingActivator.cs:line 35
at Service.Core.ResolvingActivator.CreateInstance[TService](String typeName) in Service.Core\ResolvingActivator.cs:line 69
With a full stack trace here: https://pastebin.com/0WkyHGKv
After close inspection of the stack trace, I can conclude what's going on: async.
The WcfOperationLifestyle under the covers depends on WCF's OperationContext.Current property, but this property has a thread-affinity and doesn't flow with async operations. This is something that has to be fixed in the integration library for Simple Injector; it simply doesn't support async at the moment.
Instead, wrap a decorator around your handlers that start and end a new async scope. This prevents you from having to use the WcfOperationLifestyle all together. Take a look at the ThreadScopedCommandHandlerProxy<T> implementation here to get an idea how to do this (but use AsyncScopedLifestyle instead).
I'm trying to understand how the ASP.NET Core pipeline works. I would like to use the StaticFileMiddleware and pass in some options.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var staticFileOptions = new StaticFileOptions();
app.UseMiddleware<Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware>(staticFileOptions);
}
When I run my application I get the following error
System.InvalidOperationException: A suitable constructor for type 'Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass3_0.<UseMiddleware>b__0(RequestDelegate next)
at Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
I understand that I can just use
app.UseStaticFiles(staticFileOptions);
But, as this is a learning exercise, I want to call it the other way.
This is my approach to the same problem.
Just create new class with properties which you want to pass:
public class LoggingOption
{
public bool ToLog { get; set; }
}
This is how to init
app.UseMiddleware<LoggingMiddleware>(Options.Create(new LoggingOption{ ToLog = true }));
And this is constructor
public LoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, IOptions<LoggingOption> options)
{
_next = next;
_logger = loggerFactory.CreateLogger<LoggingMiddleware>();
_toLog = options.Value.ToLog;
}
Most middleware's actually take their options not just as the pure class itself, such as in your case StaticFileOptions, but rather wrapped inside the IOptions configuration interface as IOptions<StaticFileOptions>.
Fortunately there is a nice method available to you for just this. So you can pass the return value of Microsoft.Extensions.Options.Options.Create(staticFileOptions) instead into the UseMiddleware call.
Having to wrap inside IOptions might seem redundant and so forth, but there are benefits to it, such as automatically reloading values when your configuration source (file system, Azure App Configration, etc etc) changes.
Instead of
app.UseMiddleware<Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware>(staticFileOptions);
use
app.UseMiddleware<Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware>(Microsoft.Extensions.Options.Options.Create(staticFileOptions));
(or stick the Microsoft.Extensions.Options as a using and call Options.Create)
This is how UseStaticFiles is implemented in the actual code
According to your error
System.InvalidOperationException: A suitable constructor for type 'Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
add public constructor or your constructor is private
I've an existing WPF application based on caliburn micro MVVM pattern which was using Ideablade/cocktail for accessing to database. Now I've switched to servicestack and I was keeping on cocktail just for the composition pattern. Since I've noticed it takes quite a bit long to start the application I've done some test and Ninject performs better.
I find extremly usefull the MEF approach of defining the Export/ImportingConstrucor approach but and I was wondering how I can have it with Ninject... is it possible?
In my current implementation I've something as
[Export(typeof(IMyInterface))]
[Export(typeof(MyFirstViewModel))]
public class MyFirstViewModel:IMyInterface
{
[ImportingConstructor]
public MyFirstViewModel(IEventAggregator eventAggregator)รน
{
}
}
I've seend that in ninject I've to define something as
mKernel.Bind<MyFirstViewModel>().To<MyFirstViewModel>();
mKernel.Bind<MyFirstViewModel>().To<MyFirstViewModel>();
Can it be automatic?
Can I also define a funct to resolve when not found?
Thanks
StackTrace :
at Caliburn.Micro.IoC.<.cctor>b__0(Type service, String key) in c:\Users\Rob\Documents \CodePlex\caliburnmicro\src\Caliburn.Micro.Silverlight\IoC.cs:line 13
at Caliburn.Micro.IoC.Get[T](String key) in c:\Users\Rob\Documents\CodePlex\caliburnmicro\src\Caliburn.Micro.Silverlight\IoC.cs:line 32
at myApp.Modules.Core.Framework.ViewModels.myAppScreenBase`1..ctor() in c:\Projects\myApp\branches\myApp-branch-20140526\myApp\Core\Framework\ViewModels\myAppScreenBase.cs:line 44
at myApp.Modules.Core.Framework.ViewModels.myAppSimpleScreen`1..ctor() in c:\Projects\myApp\branches\myApp-branch-20140526\myApp\Core\Framework\ViewModels\myAppSimpleScreen.cs:line 8
at myApp.Modules.AdE.ViewModels.CMATCLIDDelegheViewModel..ctor(IAdERepository repository, IDialogManager dialogManager, ICommonRepository commonRepository) in c:\Projects\myApp\branches\myApp-branch-20140526\myApp\Modules.AdE\ViewModels\CMATCLIDDelegheViewModel.cs:line 56
at DynamicInjector1033b54d439c44dbaa064db1c7e82f18(Object[] )
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()
RepositoryExport :
public class RepositoryBindingGenerator : IBindingGenerator
{
public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
{
foreach (var attribute in type.GetCustomAttributes(typeof(RepositoryAttribute), false)
.OfType<RepositoryAttribute>())
{
yield return bindingRoot
.Bind(attribute.ContractType ?? type)
.To(type).InSingletonScope();
}
}
}
but I got this compile error
Error 19 Cannot implicitly convert type 'Ninject.Syntax.IBindingNamedWithOrOnSyntax' to 'Ninject.Syntax.IBindingWhenInNamedWithOrOnSyntax'. An explicit conversion exists (are you missing a cast?)
Depending on the configuration of ninject (by default its enabled) you don't need to bind a type to itself, ninject will resolve it automatically. So mKernel.Bind<MyFirstViewModel>().To<MyFirstViewModel>(); is superfluous. Remark: Creating the binding anyway also works.
However, if you want to bind Bar to IFoo or Foo to IFoo you need to bind it.
With it you can tell ninject to look for all types with an [Export] attribute and bind these.
Here comes the ninject conventions extension to the rescue. Get the ninject.extensions.conventions nuget package.
Then create a convention binding:
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses()
.WithAttribute<ExportAttribute>()
.BindWith<ExportBindingGenerator>());
public class ExportBindingGenerator : IBindingGenerator
{
public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
{
foreach (var attribute in type.GetCustomAttributes<ExportAttribute>())
{
yield return bindingRoot
.Bind(attribute.ContractType)
.To(type);
}
}
}
Things get a bit more complicated when you need to also use the [ImportingConstructor] attribute to tell ninject which constructor to use. But i would suppose that you don't need it, since Ninject's auto-constructor-selection. What you can do however is replace all [ImportingConstructor] attributes with Ninject's [Inject] attribute which does exactly the same.
Notes:
You may need to use another method than .FromThisAssembly() to specify all the assemblies which contain the implementation types.
If the implementation types are not public, you need to add IncludeNonePublicTypes() to the convention.
To cross the language boundary in Java side the class to be serialized needs to implement the DataSerializable interface; and in order to let the deserializer in c# know what class it is , we need to register a classID. Following the example, I write my class in Java like this:
public class Stuff implements DataSerializable{
static { // note that classID (7) must match C#
Instantiator.register(new Instantiator(Stuff.class,(byte)0x07) {
#Override
public DataSerializable newInstance() {
return new Stuff();
}
});
}
private Stuff(){}
public boolean equals(Object obj) {...}
public int hashCode() {...}
public void toData(DataOutput dataOutput) throws IOException {...}
public void fromData(DataInput dataInput) throws IOException, ClassNotFoundException { ...}
}
It looks OK but when I run it I get this exception:
[warning 2012/03/30 15:06:00.239 JST tid=0x1] Error registering
instantiator on pool:
com.gemstone.gemfire.cache.client.ServerOperationException: : While
performing a remote registerInstantiators at
com.gemstone.gemfire.cache.client.internal.AbstractOp.processAck(AbstractOp.java:247)
at
com.gemstone.gemfire.cache.client.internal.RegisterInstantiatorsOp$RegisterInstantiatorsOpImpl.processResponse(RegisterInstantiatorsOp.java:76)
at
com.gemstone.gemfire.cache.client.internal.AbstractOp.attemptReadResponse(AbstractOp.java:163)
at
com.gemstone.gemfire.cache.client.internal.AbstractOp.attempt(AbstractOp.java:363)
at
com.gemstone.gemfire.cache.client.internal.ConnectionImpl.execute(ConnectionImpl.java:229)
at
com.gemstone.gemfire.cache.client.internal.pooling.PooledConnection.execute(PooledConnection.java:321)
at
com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.executeWithPossibleReAuthentication(OpExecutorImpl.java:646)
at
com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.execute(OpExecutorImpl.java:108)
at
com.gemstone.gemfire.cache.client.internal.PoolImpl.execute(PoolImpl.java:624)
at
com.gemstone.gemfire.cache.client.internal.RegisterInstantiatorsOp.execute(RegisterInstantiatorsOp.java:39)
at
com.gemstone.gemfire.internal.cache.PoolManagerImpl.allPoolsRegisterInstantiator(PoolManagerImpl.java:216)
at
com.gemstone.gemfire.internal.InternalInstantiator.sendRegistrationMessageToServers(InternalInstantiator.java:188)
at
com.gemstone.gemfire.internal.InternalInstantiator._register(InternalInstantiator.java:143)
at
com.gemstone.gemfire.internal.InternalInstantiator.register(InternalInstantiator.java:71)
at com.gemstone.gemfire.Instantiator.register(Instantiator.java:168)
at Stuff.(Stuff.java)
Caused by: java.lang.ClassNotFoundException: Stuff$1
I could not figure out why, is there anyone who has experience can help? Thanks in advance!
In most configurations GemFire servers need to deserialize objects in order to index them, run queries and call listeners. So when you register instantiator the class will be registered on all machines in the Distributed System. Hence, the class itself must be available for loading everywhere in the cluster.
As exception stack trace says the error happens on a remote node.
Check if you have the class Stuff on all machines participating in the cluster. At least on cache servers.
Pulling my hair out trying to debug this one. Earlier this morning, this code was working fine, and I can't see what I've changed to break it. Now, whenever I try to open an nHibernate session, I'm getting the following error:
Test method BCMS.Tests.Repositories.BlogBlogRepositoryTests.can_get_recent_blog_posts threw exception: System.TypeInitializationException: The type initializer for 'NHibernate.Cfg.Environment' threw an exception. ---> System.Runtime.Serialization.SerializationException: Type is not resolved for member 'Castle.DynamicProxy.Serialization.ProxyObjectReference,Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f'..
Any thoughts on how to debug what's going on here?
I hit the same issue as you - in my case it was with NLog's static method:
LogManager.GetCurrentClassLogger()
I'd replaced the current thread's principal with a Rhinomocks stub:
var identity = MockRepository.GenerateStub<IIdentity>();
identity.Stub(x => x.IsAuthenticated).Return(true);
var principal = MockRepository.GenerateStub<IPrincipal>();
principal.Stub(x => x.Identity).Return(identity);
Thread.CurrentPrincipal = principal;
Running unit tests for my code threw the same exception from the original question.
The stack trace:
at System.AppDomain.get_Evidence()
at System.AppDomain.get_EvidenceNoDemand()
at System.AppDomain.get_Evidence()
at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String& typeName)
at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at NLog.Config.XmlLoggingConfiguration.get_AppConfig()
at NLog.LogFactory.get_Configuration()
at NLog.LogFactory.GetLogger(LoggerCacheKey cacheKey)
at NLog.LogFactory.GetLogger(String name)
at NLog.LogManager.GetCurrentClassLogger()
at MyClassHere...
So as you can see from the stack trace an attempt to read the config file is made, which won't work - why? Because the now mocked current principal is no longer the WindowsPrincipal that we had originally - it's now a mocked principal which won't have any sort of windows file access.
Thinking off the cuff here's a couple of ways to fix this issue.
Inject the logger into my class so that it can be stubbed (I probably should be doing this anyway I suppose..). This would allow me to use a stub for the Thread principal.
Modify the existing WindowsPrincipal (or create another based on it) on the thread to add in the roles required to call my methods.
-- UPDATE --
To fix my issue, in the end I decided to run with my first suggestion above. To avoid writing my own abstraction of the NLog Logger I just leveraged what was offered from Common.Logging. Class constructors now accept an ILog as one of their parameters, and the Unity config to inject the logger just looks like this:
container.RegisterType<ILog>(new TransientLifetimeManager(), new InjectionFactory(x => LogManager.GetCurrentClassLogger()));
Meanwhile, my unit tests now allow me to pass in a mocked logger.
var logger = MockRepository.GenerateStub<ILog>();
Some more info... it seems to be related to switching the Thread.CurrentPrincipal to a mocked IPrincipal implementation. I do all my security checks in my domain model inside the entities. The entity's methods check Thread.CurrentPrincipal.IsInRole() before modifying properties on the entity.
So, in order to test the entity's methods, I have to set different users (contributor user, moderator user, etc.) before I make my entity method calls.
I haven't figured out why this was working fine yesterday.
Here's an example of my Mocked IPrincipal:
private static IPrincipal _blogContributorUser = null;
public static IPrincipal BlogContributorUser
{
get
{
if (null == _blogContributorUser)
{
var identity = MockRepository.GenerateStub<IIdentity>();
identity.Stub(p => p.Name).Return("BlogContributor").Repeat.Any();
var principal = MockRepository.GenerateStub<IPrincipal>();
principal.Stub(p => p.Identity).Return(identity).Repeat.Any();
principal.Stub(p => p.IsInRole(UserRoles.BlogContributor)).Return(true).Repeat.Any();
principal.Stub(p => p.IsInRole(UserRoles.CommentContributor)).Return(true).Repeat.Any();
principal.Stub(p => p.IsInRole(UserRoles.TagContributor)).Return(true).Repeat.Any();
_blogContributorUser = principal;
}
return _blogContributorUser;
}
}
I have the same issue. It looks like that it has trouble reading the config file, since CurrentPrincipal is changed. I have moved all that has to be initialized from the config file, before replacing the CurrentPrincipal (for example, opened NHibernate session, initialized Unity and that kind of stuff), and everything works after that. Of course, this is not a solution, just a workaround figured out by a desperate man.
Errors like this usually indicate versioning issues.
What I suspect may be happening is that both RhinoMocks and NHibernate are making use of Castle.DynamicProxy type, but they are asking for different versions of that type.
Did you recently uprade RhinoMocks or NHibernate to a newer version?
If this isn't the issue, then more information would be helpful - do all tests fail, or just this particular one?
edit You may also wish to try adding these lines to your Properties\AssemblyInfo.cs file:
[assembly: InternalsVisibleTo("Rhino.Mocks")]
[assembly: InternalsVisibleTo("Castle.DynamicProxy")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
In case the error is related to mocking IPrincipal and/or IIdentity with RhinoMocks or Moq the solution is actually quite simple: don't use those frameworks but create simple fake types instead.
Here is an example for a simple "allow everything" implementation:
public class FakeIdentity : IIdentity
{
public string Name { get { return "IntegrationTest"; } }
public string AuthenticationType { get { return "Kerberos"; } }
public bool IsAuthenticated { get { return true; } }
}
public class FakePrincipal : IPrincipal
{
public FakePrincipal() { this.Identity = new FakeIdentity(); }
public IIdentity Identity { get; private set; }
public bool IsInRole(string role) { return true; }
}
If you need more complexity take a look at the System.Security.Principal.GenericPrincipal class.