I have a WCF service that is setup to be hosted within a unity container. I was intending to use this container to perform method interception. The problem is I cannot get my interceptor to fire...
First here the definition of my interceptor attribute and handler:
[AttributeUsage(AttributeTargets.Method)]
public class PCSecurityAttribute : HandlerAttribute
{
public PCSecurityAttribute(Modules module, int modulePermission)
{
SecurityModule = module;
SecurityModulePermission = modulePermission;
}
public Modules SecurityModule
{
get;
set;
}
public int SecurityModulePermission
{
get;
set;
}
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new PCSecurityCallHandler(0, SecurityModule,
SecurityModulePermission);
}
}
using System.ServiceModel.Security;
using MHC.PracticeConnect.Contract.Data.Security;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace MHC.PracticeConnect.Service
{
public class PCSecurityCallHandler : ICallHandler
{
private Modules securityModule;
private int securityModulePermission;
public PCSecurityCallHandler(Modules module, int modulePermission)
{
securityModule = module;
securityModulePermission = modulePermission;
Order = 0;
}
public PCSecurityCallHandler(int order, Modules module,
int modulePermission)
{
securityModule = module;
securityModulePermission = modulePermission;
Order = order;
}
public IMethodReturn Invoke(IMethodInvocation input,
GetNextHandlerDelegate getNext)
{
bool validPermission = false;
// check security permission
IMethodReturn result;
if (validPermission)
result = getNext().Invoke(input, getNext);
else
throw new SecurityAccessDeniedException(
"The current user does not have security " +
"permissions to call this module.");
return result;
}
public int Order
{
get;
set;
}
}
}
In my host I've tried to configure it to use interception to no avail... HELP!!!!
public class DocumentTemplateServiceHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType,
Uri[] baseAddresses)
{
UnityServiceHost host =
new UnityServiceHost(serviceType, baseAddresses);
UnityContainer unity = new UnityContainer();
host.Container = unity;
host.Container.AddNewExtension<Interception>(); ;
host.Container.RegisterType<IDocumentTemplateService,
DocumentTemplateService>().Configure<Interception>().
SetInterceptorFor<IDocumentTemplateService>(
new TransparentProxyInterceptor());
return host;
}
}
What am I doing wrong here?
You might want to check out using WCF behaviors. Here's links that might be useful.
http://msdn.microsoft.com/en-us/magazine/cc136759.aspx
AND
http://www.global-webnet.net/blogengine/post/2009/01/03/Integrating-IIS-WCF-and-Unity.aspx
-Bryan
I've created something that does exactly what you're looking for. I've placed it on CodePlex:
http://wcfaop.codeplex.com/
Basically, you have to create your own InstanceProvider which will then create the WCF service object from a Unity container and allow you to do interception.
Related
I would like to write xunit test case of below method. Could you please suggest alternate design so i can write xunit test case with minimum change in my current project.
public ActionResult Index(int id = 0, AssetFilterType filter = AssetFilterType.All)
{
using (var tracer = new Tracer("AssetController", "Index"))
{
RemoveReturnUrl();
ViewBag.JobId = id;
var response = ContextFactory.Current.GetDomain<EmployeeDomain>().GetEmployeeFilterAsync(id,
CurrentUser.CompanyId, filter); // Not able write unit test case , please suggest alternate design.
return View("View", response);
}
}
current design is as follow
public interface IDomain
{
}
public interface IContext
{
D GetDomain<D>() where D : IDomain;
string ConnectionString { get; }
}
public class ApplicationContext : IContext
{
public D GetDomain<D>() where D : IDomain
{
return (D)Activator.CreateInstance(typeof(D));
}
public string ConnectionString
{
get
{
return "DatabaseConnection";
}
}
}
public class ContextFactory
{
private static IContext _context;
public static IContext Current
{
get
{
return _context;
}
}
public static void Register(IContext context)
{
_context = context;
}
}
//var response = ContextFactory.Current.GetDomain**< EmployeeDomain>**().GetEmployeeFilterAsync(id,
CompanyId, filter);
This line serve purpose to call specific class method i.e GetEmployeeFilterAsync from EmployeeDomain. Although it is very handy and widely used in our application but due to design issue i am not able to write unit
test case.
Could you please suggest design so with the minimum change we can write unit test case.
Don't use the Service Locator anti-pattern, use Constructor Injection instead. I can't tell what AssetDomain is from the OP, but it seems as though it's the dependency that matters. Inject it into the class:
public class ProbablySomeController
{
public ProbablySomeController(AssetDomain assetDomain)
{
AssetDomain = assetDomain;
}
public AssetDomain AssetDomain { get; }
public ActionResult Index(int id = 0, AssetFilterType filter = AssetFilterType.All)
{
using (var tracer = new Tracer("AssetController", "Index"))
{
RemoveReturnUrl();
ViewBag.JobId = id;
var response = AssetDomain.GetAssetFilterAsync(id, CurrentUser.CompanyId, filter);
return View("View", response);
}
}
}
Assuming that AssetDomain is a polymorphic type, you can now write a test and inject a Test Double:
[Fact]
public void MyTest()
{
var testDouble = new AssetDomainTestDouble();
var sut = new ProbablySomeController(testDouble);
var actual = sut.Index(42, AssetFilterType.All);
// Put assertions here
}
step1 : Required library
step 2 : When the application starts , register required domain like
protected void Application_Start()
UnityConfig.RegisterComponents();
Step 3: create one static class and register all your domain
example
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
Initialize domain which will injected in controller
container.RegisterType<IPricingDomain, PricingDomain>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
step 4 :
so you can inject respective interface in constructor
in controller file.
goal : get rid of below any pattern in your project.
and start writing unit test cases.
I am trying to create a complex session wrapper in .NET Core 3.1. I ran into an issue where my variables are not being set. This is the way I set up the session wrapper class.
public class SessionWrapper : ISessionWrapper
{
private static IHttpContextAccessor context;
public SessionWrapper(IHttpContextAccessor _context)
{
context = _context;
}
public static Course Course
{
get
{
var key = context.HttpContext.Session.GetString("course");
if (key == null)
{
return default;
}
else
{
return JsonConvert.DeserializeObject<Course>(key);
}
}
set
{
if(value != null)
{
context.HttpContext.Session.SetString("course", JsonConvert.SerializeObject(value));
}
}
}
}
I configured my services to use session and the sessionwrapper.
services.AddDistributedMemoryCache();
services.AddSession();
services.AddHttpContextAccessor();
services.AddScoped<ISessionWrapper, SessionWrapper>();
I configured the pipeline to use session
app.UseSession();
In my controller, I am initializing course and set the session wrapper. Then, I am setting the course id to 4. It's not complaining, but the course id is not being set. It's always null. I've been looking at it for so and is getting frustrated. What am I missing here?
Course myCourse = new Course();
SessionWrapper.Course = myCourse;
SessionWrapper.Course.Id = "4"
I feel like your wrapper in itself isn't really the best approach to do this. A self-aware subclass of Course that has the 'know how' to store itself in Session, seems more logical to me. That way you are freeing your controller(s) from the responsibility for managing the persistence.
public abstract class Course
{
public abstract int Id { get; set; }
}
public class SessionCourse : Course
{
private int _id;
public override int Id
{
get => _id;
set { _id = value; UpdateSession(); }
}
// The GetCourse method is a factory for creating the SessionCourse objects
// and providing it with a ISession object so they can store themselves.
public static Course GetCourse(IServiceProvider services)
{
ISession session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
SessionCourse course = session?.GetJson<SessionCourse>("Course") ?? new SessionCourse();
course.Session = session;
return course;
}
[JsonIgnore]
private ISession Session { get; set; }
private void UpdateSession() {
Session.SetJson("Course", this);
}
}
Now the trick is to satisfy requests for the Course object with the SessionCourse object that will store itself in session. You can do that by adding a scoped service with a lambda expression for the course object. The result is that requests for the Course service will return the SessionCourse object.
services.AddScoped<Course>(sp => SessionCourse.GetCourse(sp));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
So the benefit of creating this kind of service is that it allows you to simplify the controllers where Course objects are used.
public class CourseController : Controller
{
private Course course;
public CartController(Course courseService)
{
course = courseService;
}
public void SetCourseId()
{
course.Id = "4";
}
SessionExtension.cs defines extension methods for adding objects to the session.
public static class SessionExtensions {
public static void SetJson(this ISession session, string key, object value) {
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetJson<T>(this ISession session, string key) {
var sessionData = session.GetString(key);
return sessionData == null ? default(T) : JsonConvert.DeserializeObject<T>(sessionData);
}
}
My first time using .net core.
I was able to build a functioning ,net core web application that calls data from my SQL server using Onion Layers. My layout is as below:
Architecture
Core
Application Services
Domain Services
Core.Entity
Infrastructure
UI
API
CemeteryAPI
Web
MVC Web Application
My HomeController has a PageModel with a Complex Type of Search, which consists of about 5 or so ints another 5-6 Lists. In the past I would have done:
var model = new Models.HomePageModel
{
Search = new Business.Search()
};
public partial class Search
{
public String Surname { get; set; }
public String Forename { get; set; }
public String Initials { get; set; }
//etc.
}
I have registered my Services on my startup in ConfigureServices and have attempted to inject this way
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICemeteryRepository, CemeteryRepository>();
services.AddScoped<ICountryRepository, CountryRepository>();
//etc
services.AddScoped<ICemeteryService, CemeteryService>();
services.AddScoped<ICountryService, CountryService>();
}
CemeteryService
//ApplicationService
public class CemeteryService : AbstractUnitOfWorkService, ICemeteryService
{
public CemeteryService(IUnitOfWork uow) : base(uow) { }
public int Count()
{
return _unitOfWork.CemeteryRepository.Count();
}
public Cemetery Get(int id)
{
return _unitOfWork.CemeteryRepository.Get(id);
}
public List<Cemetery> List()
{
return _unitOfWork.CemeteryRepository.GetAll().ToList();
}
}
ICemeterRepository
//DomainService
public interface ICemeteryRepository : IRepository<Cemetery>
{
}
CemeteryRepository
public class CemeteryRepository : BaseRepository, ICemeteryRepository
{
public CemeteryRepository(SAWGPDBContext context) : base(context) { }
public int Count()
{
return _context.Cemetery.Count();
}
public Cemetery Get(int id)
{
return _context.Cemetery.Find(id);
}
public IEnumerable<Cemetery> GetAll()
{
return _context.Cemetery;
}
//etc
}
ICemeteryInterface
public interface ICemeteryService
{
int Count();
List<Cemetery> List();
//etc
}
public ActionResult Index([FromServices] ICasualtyService _CasualtyService, IPhotoService _PhotoService, ICountryService _CountryService, ICemeteryService _CemeteryService, IRegimentService _RegimentService)
var model = new Models.HomePageModel
{
Search = new SearchPageModel(_PhotoService, _CasualtyService, _CountryService, _CemeteryService, _RegimentService, )
};
This looked wrong but I couldn't find any proper examples as I wasn't sure what to look for exactly. The above returns
Model bound complex types must not be abstract or value types and must
have a parameterless constructor.
I presume I need to build a SearchService but I'm not entirely clear how to build one for a complex type. Any pointers would be appreciated.
Hopefully this is an easy one. I'm wondering if this is possible - perhaps it is not. I'm attempting to self-host a WCF service (in my example below it is a console application). The service does not have a default constructor. It only contains a single parameter signature constructor. I need the service to be able to handle user sessions. Currently I am using Ninject DI. Here is a simple code solution I came up with to demonstrate my issue:
using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using Ninject.Modules;
namespace ConsoleApplication1
{
public class Program
{
static void Main()
{
using (var webServiceHost = new WebServiceHost(typeof(MyWcf)))
{
var webHttpBinding = new WebHttpBinding();
var uri = new Uri("http://localhost:8000/");
webServiceHost.AddServiceEndpoint(typeof(IMyWcf), webHttpBinding, uri);
webServiceHost.Open();
Console.WriteLine("Service is ready...");
Console.ReadKey();
}
}
}
[ServiceContract]
public interface IMyWcf
{
[OperationContract, WebGet(UriTemplate = "")]
string HelloWorld();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyWcf : IMyWcf
{
private readonly IMessage _customMessage = new Message("Default Message.");
public MyWcf(IMessage message)
{
_customMessage = message;
}
public string HelloWorld()
{
return _customMessage.Text;
}
}
public interface IMessage
{
string Text { get; }
}
public class Message : IMessage
{
public Message (string message)
{
Text = message;
}
public string Text { get; set; }
}
public class NinjectSetup : NinjectModule
{
public override void Load()
{
Bind<IMessage>().To<Message>()
.WithConstructorArgument("message", "Injected String Message.");
}
}
}
Obviously commenting out the parameterized constructor allows the service to run. But that does me no good. I don't want to use ServiceHostFactory because that apparently requires me to have a .svc/IIS. Is there a way around this? Can I just create a new MyWebServiceHost that inherits from WebServiceHost and override some method that will create a instance for the service?
Using Ruben's suggestion (in the comments) above, I was able to locate a working example within the Ninject.Extensions.Wcf source repository.
I'm using a PostSharp method attribute to do authorisation and auditing on my WCF service. It's working properly but now I'm trying to get my unit tests working with the attribute and am struggling to find a way to mock and inject the properties on the attribute.
My attribute is as below.
[Serializable]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class AuthoriseAndAuditAttribute : OnMethodBoundaryAspect
{
private static ILog logger = AppState.logger;
private static Ninject.IKernel _kernel = MyKernel.Kernel;
private UserRoleTypesEnum _requiredRole = UserRoleTypesEnum.None;
[Inject]
public IServiceAuthToken _serviceAuthToken { get; set; }
[Inject]
public UserSessionDataLayer _userSessionDataLayer { get; set; }
public AuthoriseAndAuditAttribute(UserRoleTypesEnum role = UserRoleTypesEnum.None)
{
_requiredRole = role;
_kernel.Inject(this);
}
public override void OnEntry(MethodExecutionArgs args)
{
// Get the user's session from cookie.
UserSession userSession = GetUserSession();
// Check that user is in the required role.
bool isAuthorised = (_requiredRole == UserRoleTypesEnum.None || (userSession != null && userSession.Roles.Contains(_requiredRole)));
if (!isAuthorised)
{
logger.Warn("Not authorised for " + args.Method.Name + ".");
throw new UnauthorizedAccessException();
}
else if (userSession != null)
{
Thread.CurrentPrincipal = new MyPrincipal(userSession);
}
}
private UserSession GetUserSession()
{
if (_serviceAuthToken != null)
{
string sessionID = _serviceAuthToken.GetSessionID();
if (!sessionID.IsNullOrBlank())
{
return _userSessionDataLayer.GetForSessionID(sessionID);
}
}
return null;
}
}
I have a singleton class setting up the Ninject kernel:
public class MyKernel
{
public static StandardKernel Kernel { get; set; }
static MyKernel()
{
Kernel = new StandardKernel();
Kernel.Bind<IServiceAuthToken>().To<ServiceAuthToken>();
Kernel.Bind<UserSessionDataLayer>().To<UserSessionDataLayer>();
}
}
In my WCF service I use the PostSharp attribute as below:
[AuthoriseAndAudit(UserRoleTypesEnum.Operator)]
public JSONResult<bool> IsAliveAuthorised()
{
return new JSONResult<bool>() { Success = true, Result = true };
}
And in my unit test I'm using RhinoMocks to try and mock the two DI properties in the attribute.
[TestMethod]
public void IsAliveAuthorisedIsAuthorisedTest()
{
var mockServiceAuthToken = MockRepository.GenerateStrictMock<ServiceAuthToken>();
mockServiceAuthToken.Stub(x => x.GetSessionID()).Return("x");
var mockUserSessionDataLayer = MockRepository.GenerateStrictMock<UserSessionDataLayer>();
mockUserSessionDataLayer.Stub(x => x.GetForSessionID(Arg<string>.Is.Anything)).Return(new UserSession());
MyKernel.Kernel.Bind<ServiceAuthToken>().ToConstant(mockServiceAuthToken);
MyKernel.Kernel.Bind<UserSessionDataLayer>().ToConstant(mockUserSessionDataLayer);
var service = new MyService();
Assert.IsTrue(service.IsAliveAuthorised().Result);
}
The issue I have is the mock objects in the unit test are never ending up being set as the properties on the attribute. What am I doing wrong or conversely is there a better way to do unit testing on a PostSharp attribute? Also bearing in mind I really want to minimise the use of the Ninject DI to the bare minimum.
Instead of using the [Inject] attribute on your properties, redefine them like this:
public IServiceAuthToken _serviceAuthToken { get { return _kernel.Get<IServiceAuthToken>(); } }
public UserSessionDataLayer _userSessionDataLayer { get { return _kernel.Get<UserSessionDataLayer>(); } }
Also, in your test method you need to re-bind (note also that you were using the concrete type ServiceAuthToken in the first bind instead of the interface IServiceAuthToken):
MyKernel.Kernel.Rebind<IServiceAuthToken>().ToConstant(mockServiceAuthToken);
MyKernel.Kernel.Rebind<UserSessionDataLayer>().ToConstant(mockUserSessionDataLayer);