Here is an interesting question: Why does the garbage collection not work for the simple unit test initialization example below? At least for me running VS2013 .NET 4.5 I eventually run out of memory and get a out of memory exception.
The shimmed method is needed, without that the garbage collector works just fine also inside the ShimsContext.
This is boiled down from one of my tests where a large xml file was parsed with several million temporary object creations, eventually leaving me without any memory.
Class under test
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MemoryTester
{
public class Program
{
static void Main(string[] args)
{
}
static void MethodToFake()
{
Console.WriteLine("This is the original method");
}
}
public class OutsideClass
{
public OutsideClass()
{
}
~OutsideClass()
{
}
}
}
Unit test class
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.QualityTools.Testing.Fakes;
namespace Tests
{
[TestClass]
public class MemoryTests
{
protected IDisposable Context;
[TestInitialize]
public void InitTest()
{
using (ShimsContext.Create())
{
MemoryTester.Fakes.ShimProgram.MethodToFake = () =>
{
Console.WriteLine("This is the shimmed method");
};
while (true)
{
//This will never be garbage collected, why?
MemoryTester.OutsideClass nc = new MemoryTester.OutsideClass();
}
}
while (true)
{
//Outside of ShimsContext, we will garbage collect just fine
MemoryTester.OutsideClass nc = new MemoryTester.OutsideClass();
}
}
[TestMethod]
public void AttributeSerializerMemoryTest()
{
Assert.IsTrue(true);
}
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
}
}
Related
Right now my code looks like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
namespace City
{
public static class MS
{
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
private static void NotifyStaticPropertyChanged(string propertyName)
{
if (StaticPropertyChanged != null)
StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}
private static int timerSeconds;
public static int TimerSeconds
{
get { return timerSeconds; }
set { timerSeconds = value; NotifyStaticPropertyChanged("TimerSeconds"); }
}
}
}
and this XAML
<Label x:Name="timer" Text="{Binding Source={x:Static local:MS.TimerSeconds}}" />
</Grid>
The code works but in a previous questions one of the posters said this:
I would strongly recomend you to not use static class to keep data and
bind something to them. Stange things may happen - in your code you
are calling event with null sender. Event if it's working right now,
it may not work with future releases of Xamarin.Forms. At least use
singleton pattern - it allows you to implement INotifyPropertyChanged
interface
Can someone explain or show me a very short example of what is meant here. Should I for example create a class in the application start area and how could I change that to implement INotifyPropertyChanged?
Here is what you can do. Implement below and if you need a singleton (I am not sure why as I don't know your design) you access it as "MSSingleton.Instance" but I would try to avoid even singleton and just create MS object when you need it.
public class MSSingleton : INotifyPropertyChanged
{
//if you need singleton
static MSSingleton _instance = null;
public static MSSingleton Instance
{
get
{
if (_instance == null)
_instance = new MSSingleton();
return _instance;
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private int timerSeconds;
public event PropertyChangedEventHandler PropertyChanged;
public int TimerSeconds
{
get { return timerSeconds; }
set { timerSeconds = value; OnPropertyChanged("TimerSeconds"); }
}
}
I take NullReferenceException when I want to add addJsonFile. I made exaclty what lynda(http://www.lynda.com/ASP-NET-tutorials/Dynamically-control-behavior-custom-configuration/368051/431234-4.html) said.
(screenShot)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNet.Diagnostics;
using Microsoft.Framework.Internal;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.ConfigurationModel.Json;
namespace PortalDemo
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
var config = new Configuration();
config.AddEnvironmentVariables();
config.AddJsonFile("config.json");//Here
if (config.Get("debug") == "True")
{
app.UseRuntimeInfoPage();
app.UseDeveloperExceptionPage();
}
app.UseExceptionHandler("/home/errorPage");
app.UseMvc(routes=>
routes.MapRoute("Default","{controller=Home}/{action=Index}/{id?}"));
app.UseStaticFiles();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
Try the following code.
public class Startup
{
public Startup(IApplicationEnvironment appEnv)
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json", false);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
}
I'm using this beriliant project for base of my MVC project.
But when I use WebAPI for project there is problem in IDataProtector injection.
I redesign base and upload here, and add a console project for testing authorizing with WebAPI.
This is structuremap initialization :
private static readonly Lazy<Container> _containerBuilder =
new Lazy<Container>(initStructureMap, LazyThreadSafetyMode.ExecutionAndPublication);
public static IContainer Container
{
get { return _containerBuilder.Value; }
}
return new Container(ioc =>
{
ioc.For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use(() => new DbContext());
ioc.For<IDataSerializer<AuthenticationTicket>>().Use<TicketSerializer>();
ioc.For<ISecureDataFormat<AuthenticationTicket>>().Use<SecureDataFormat<AuthenticationTicket>>();
});
and in WebApiConfig class DI is like this:
var container = StructuremapMvc.Container;
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator), new StructureMapHttpControllerActivator(container));
in my startup I create dataprotector with IAppBuilder :
public void ConfigureAuth(IAppBuilder app)
{
StructuremapMvc.Container.Configure(config =>
{
config.For<IDataProtectionProvider>()
.HybridHttpOrThreadLocalScoped()
.Use(() => app.GetDataProtectionProvider());
});
}
It start after WebApiConfig and IDataProtection not work in WebApi. my ServiceLayer is in separate project and DataProtection need to inject there.
you need add two class to your project :
1-StructureMapDependencyScope Class
using StructureMap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
namespace Project.Helpers
{
public class StructureMapDependencyScope : IDependencyScope
{
protected readonly IContainer Container;
public StructureMapDependencyScope(IContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.Container = container;
}
public void Dispose()
{
this.Container.Dispose();
}
public object GetService(Type serviceType)
{
if (serviceType == null)
{
return null;
}
try
{
return serviceType.IsAbstract || serviceType.IsInterface
? this.Container.TryGetInstance(serviceType)
: this.Container.GetInstance(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return this.Container.GetAllInstances(serviceType).Cast<object>();
}
}
}
2-StructureMapDependencyResolver Class
using StructureMap;
using System.Web.Http.Dependencies;
namespace Project.Helpers
{
public class StructureMapDependencyResolver : StructureMapDependencyScope, IDependencyResolver
{
public StructureMapDependencyResolver(IContainer container)
: base(container)
{
}
public IDependencyScope BeginScope()
{
IContainer child = this.Container.GetNestedContainer();
return new StructureMapDependencyResolver(child);
}
}
}
at the end replace this code with yours in WebApiConfig Class:
// IoC Config
var container = SmObjectFactory.Container;
// Web API configuration and services
config.DependencyResolver = new StructureMapDependencyResolver(container);
read more about Dependency Injection in ASP.NET MVC 4 and Web API by StructureMap here.
You need to explicitly register implementation of IDataProtector in the container.
Sample configuration might looks like this:
ioc.For<IDataProtector>().Use(() => new DpapiDataProtectionProvider().Create("ASP.NET Identity"));
ioc.For<ITextEncoder>().Use<Base64UrlTextEncoder>();
Bear in mind that this specific configuration might not suit your exact needs.
Hope this helps!
I'm using Castle Windsor and I'm trying to set up a cache on a TypedFactory using the decorator pattern. It works fine until I'm trying to dispose of the Windsor container (when shutting down the application). Basically, my problem is that the TypedFactory is already disposed when I'm trying to dispose of the CachedFactory.
Here is a simplified example of my problem:
using System;
using System.Collections.Generic;
using System.Threading;
using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
// Setting up the container
var container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<IItemFactory>().ImplementedBy<CachedItemFactory>(), //decorator pattern
Component.For<IItemFactory>().AsFactory(),
Component.For<IItem>().ImplementedBy<Item>().LifestyleTransient()
);
// Resolving
var itemFactory = container.Resolve<IItemFactory>();
// Desired behavior. Works as expected.
IItem item1 = itemFactory.Create("Item1");
IItem item2 = itemFactory.Create("Item2");
IItem anotherItem1 = itemFactory.Create("Item1");
Console.WriteLine("Item1 == Item2: {0}", item1 == item2); //false
Console.WriteLine("Item1 == anotherItem1: {0}", item1 == anotherItem1); //true
// Here is my problem. It throws ObjectDisposedException from _itemFactory in the Dispose function of CachedItemFactory
container.Dispose();
Console.WriteLine("End of program");
Console.ReadKey();
}
}
public interface IItem
{
string Name { get; }
}
public class Item : IItem
{
public Item(string name)
{
Name = name;
Thread.Sleep(1000); //It takes time to create this object
}
public string Name { get; private set; }
}
public interface IItemFactory
{
IItem Create(string name);
void Release(IItem item);
}
public class CachedItemFactory : IItemFactory, IDisposable
{
private readonly Dictionary<string, IItem> _cache = new Dictionary<string, IItem>();
private readonly IItemFactory _itemFactory;
public CachedItemFactory(IItemFactory itemFactory)
{
_itemFactory = itemFactory;
}
public IItem Create(string name)
{
if (!_cache.ContainsKey(name))
_cache.Add(name, _itemFactory.Create(name));
return _cache[name];
}
public void Release(IItem item)
{
}
public void Dispose()
{
foreach (var item in _cache)
{
_itemFactory.Release(item.Value);
}
_cache.Clear();
}
}
}
Any ideas of what I'm doing wrong? Any conceptual (architectural) errors?
I tried the following with no success:
Registering the TypedFactory before the CachedItemFactory (and marking the CachedItemFactory as IsDefault): not working, same error
Implementing a basic factory by hand instead of using the TypedFactory: same problem
This worked:
Implementing a basic factory by hand, registering it before the CachedItemFactory and marking the CachedItemFactory as IsDefault... but it feels wrong (fragile)...
Any comments?
Thanks a lot!
You are registering both the cached and typedfactory as singletons (implicitly).
If you register the TypeFactory as Transient it will probably (not completely sure) be disposed right after the cached factory.
However since you only try to cleanup the resolved components of the factory you could also simply omit the code in Dispose as the typed factory will release all it's components when it is released.
I am using SignalR in my MVC3 application, and since I have implemented StructureMap Dependency Injection on my controllers I would like to do the same in my hub, but I can't seem to get it working.
Please tell me what's wrong with my codes below:
SignalRSmDependencyResolver.cs
public class SignalRSmDependencyResolver : DefaultDependencyResolver
{
private IContainer _container;
public SignalRSmDependencyResolver(IContainer container)
{
_container = container;
}
public override object GetService(Type serviceType)
{
object service = null;
if (!serviceType.IsAbstract && !serviceType.IsInterface && serviceType.IsClass)
{
// Concrete type resolution
service = _container.GetInstance(serviceType);
}
else
{
// Other type resolution with base fallback
service = _container.TryGetInstance(serviceType) ?? base.GetService(serviceType);
}
return service;
}
public override IEnumerable<object> GetServices(Type serviceType)
{
var objects = _container.GetAllInstances(serviceType).Cast<object>();
objects.Concat(base.GetServices(serviceType));
return objects;
}
}
SignalRExtensionsRegistry.cs
public class SignalRExtensionsRegistry : Registry
{
public SignalRExtensionsRegistry()
{
For<IDependencyResolver>().Add<SignalRSmDependencyResolver>();
}
}
IoC.cs
public static class IoC {
public static IContainer Initialize() {
var container = BootStrapper.Initialize();
container.Configure(x =>
{
x.For<IControllerActivator>().Singleton().Use<StructureMapControllerActivator>();
});
return container;
}
}
public class StructureMapControllerActivator : IControllerActivator {
public StructureMapControllerActivator(IContainer container) {
_container = container;
}
private IContainer _container;
public IController Create(RequestContext requestContext, Type controllerType) {
IController controller = DependencyResolver.Current.GetService(controllerType) as IController;
return controller;
}
}
AppStart_Structuremap.cs
[assembly: WebActivator.PreApplicationStartMethod(typeof(StoreUI.AppStart_Structuremap), "Start")]
namespace MyNameSpace {
public static class AppStart_Structuremap {
public static void Start() {
var container = (IContainer) IoC.Initialize();
DependencyResolver.SetResolver(new StructureMapDependenceyResolver(container));
AspNetHost.SetResolver(new StructureMapDependencyResolver(container));
}
}
}
NotificationsHub.cs
[HubName("notificationsHub")]
public class NotificationsHub : Hub
{
#region Declarations
private readonly IUserService userService;
#endregion
#region Constructor
public NotificationsHub(IUserService userService)
{
this.userService = userService;
}
#endregion
public void updateServer(string message)
{
Clients.updateClient(message);
}
}
Thanks
Getting Structuremap into SignalR is actually pretty easy. First you want to create your own resolver:
StructureMap Resolver
Usings:
using SignalR.Infrastructure;
using StructureMap;
Class:
public class StructureMapResolver : DefaultDependencyResolver
{
private IContainer _container;
public StructureMapResolver(IContainer container)
{
_container = container;
}
public override object GetService(Type serviceType)
{
object service = null;
if (!serviceType.IsAbstract && !serviceType.IsInterface && serviceType.IsClass)
{
// Concrete type resolution
service = _container.GetInstance(serviceType);
}
else
{
// Other type resolution with base fallback
service = _container.TryGetInstance(serviceType) ?? base.GetService(serviceType);
}
return service;
}
public override IEnumerable<object> GetServices(Type serviceType)
{
var objects = _container.GetAllInstances(serviceType).Cast<object>();
return objects.Concat(base.GetServices(serviceType));
}
}
The idea here is to try and use your container to resolve the dependencies, if you do not have the dependency wired up, pass it through to the default resolver. This way you don't have to worry about all of the other dependencies in SignalR and can focus only on the stuff you want to inject into (Hubs, ConnectionIdFactory, MessageBus, etc.).
Bindings for Resolver and Hub
Next you will want to register this in your container (i like using registries):
Usings:
using SignalR.Infrastructure;
using StructureMap.Configuration.DSL;
Class:
public class ExtensionsRegistry : Registry
{
public ExtensionsRegistry()
{
For<IDependencyResolver>().Add<StructureMapResolver>();
}
}
Resolver Replacement
Finally you will want to tell SignalR to use your resolver instead of the default:
Global::Application_Start or WebActivator::Pre_Start
Usings:
using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;
Application_Start:
// Make sure you build up the container first
AspNetHost.SetResolver(StructureMap.ObjectFactory.GetInstance<IDependencyResolver>());
Silly Hub with injected dependencies
Now you can just inject any dependencies your container knows about into the hubs themselves:
[HubName("defaultHub")]
public class DefaultHub : Hub, IDisconnect
{
private readonly IRepository _repo;
public DefaultHub(IRepository repo)
{
_repo = repo;
}
public void Connect()
{
Caller.setUser(Context.ConnectionId);
Clients.addMessage(string.Format("{0} has connected", Context.ConnectionId));
}
public void MessageSender(string message)
{
Caller.addMessage(_repo.RepositoryMessage());
Clients.addMessage(message);
}
public Task Disconnect()
{
var clientId = this.Context.ConnectionId;
return Task.Factory.StartNew(() => { Clients.addMessage(string.Format("{0} has disconnected", clientId)); });
}
}
Have you followed the instructions here:- https://github.com/SignalR/SignalR/wiki/Extensibility ?
You'll need to use AspNetHost.SetResolver.
I know this is an old thread, but for those who are wondering where is the AspNetHost.SetResolver in the newer version of signalR, you can use this in the App_Start StructuremapMvc.cs:
public static void Start() {
IContainer container = IoC.Initialize();
GlobalHost.DependencyResolver = new SignalRSmDependencyResolver(container); // for signalR
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
}
Add something like this to a file in your App_Start folder. This code snippet is for Ninject, so just replace AspNetHost.SetResolver()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Ninject;
using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;
using SignalR.Ninject;
using Web.Models;
[assembly: WebActivator.PreApplicationStartMethod(typeof(Web.App_Start.NinjectSignalR), "Start")]
namespace Web.App_Start
{
public static class NinjectSignalR
{
public static void Start()
{
IKernel kernel = CreateKernel();
// switch this line to the structuremap resolver
AspNetHost.SetResolver(new NinjectDependencyResolver(kernel));
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
RegisterServices(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
// add your services here
//kernel.Bind<IRepository>().To<Repository>();
}
}
}