I have the following StructureMap registrations that work in version 2.6.4 and I'm finally upgrading to the latest SM (3.1.2 as of this writing). And need to update it since there doesn't appear to be a IContext.BuildStack anymore.
Here is the old working version with 2.6.4:
initialization.For(typeof(IRepository<,>))
.Use(context =>
{
var genericArgs = context.BuildStack.Current.RequestedType.GetGenericArguments();
return RepositoryFactory.GetInstance(genericArgs[0], genericArgs[1], repositoryName);
}
);
So I figured that changing it to this would work:
initialization.For(typeof (IRepository<,>))
.Use("IRepository<,>", context =>
{
var genericArgs = context.ParentType.GetGenericArguments();
return RepositoryFactory.GetInstance(genericArgs[0], genericArgs[1],
repositoryName);
}
);
But context.ParentType is null. When I look at context.RootType it is set to System.Object which is obviously not what I want.
My test code to get an instance of this repository is:
var userRepository = ObjectFactory.GetInstance<IRepository<User, Guid>>();
I don't see any other property that has this information, but I'm guessing I am missing something.
You are not missing something. On GitHub someone posted a simular question: https://github.com/structuremap/structuremap/issues/288.
Jeremy Miller, the author of structuremap, responded:
It's going to have to be new development. It'll have to come in a 3.2 version.
The suggested workaround is to create a custom instance and override the ClosingType method. You can do this as follows:
public class CustomInstance : Instance
{
public override IDependencySource ToDependencySource(Type pluginType)
{
throw new NotImplementedException();
}
public override Instance CloseType(Type[] types)
{
var repository = RepositoryFactory.GetInstance(types[0], types[1], repositoryName);
return new ObjectInstance(repository);
}
public override string Description
{
get { throw new NotImplementedException(); }
}
public override Type ReturnedType
{
get { return typeof (IRepository<,>); }
}
}
Now, you only have to connect the open generic type to the closing type like this:
initialization.For(typeof (IRepository<,>)).Use(new CustomInstance());
I added a new example to the StructureMap 3 codebase for this scenario based on your question:
https://github.com/structuremap/structuremap/blob/master/src/StructureMap.Testing/Acceptance/builder_for_open_generic_type.cs
I have to ask though, what's the purpose of something like RepositoryBuilder if you're using an IoC container?
Anyway, this implementation should be more efficient than the older Reflection-heavy approach.
Related
Here's what I'm doing so far (code simplified):
public class MyRegistrationSource : IRegistrationSource
{
public MyRegistrationSource(ContainerBuilder builder /*,...*/)
{
// ...
this.builder = builder;
}
public IEnumerable<IComponentRegistration> RegistrationsFor(
Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
// Some checks here
var interfaceType = serviceWithType.ServiceType;
var implementorType = FindTheRightImplementor(interfaceType);
if (myRegisterConditionSatisfied)
{
return Register(implementorType, interfaceType);
}
return Empty;
}
private IEnumerable<IComponentRegistration> Register(Type concrete, Type #interface)
{
var regBuilder = builder.RegisterType(concrete).As(#interface).IfNotRegistered(#interface);
return new[] { regBuilder.CreateRegistration() };
}
}
Then, at startup I'm doing something like
builder.RegisterSource(
new NonRegisteredServicesRegistrationSource(builder/*, ...*/));
The above is intended to register those matching services only when there's no previous registration. I tried doing the registration without using the ContainerBuilder but couldn't get it to work.
This is working but are there any issues in passing-in the ContainerBuilder instance to the RegistrationSource?
Thanks!
I'd probably argue against passing in a ContainerBuilder.
Every type you register in your source will add a callback to a list of callbacks inside the Container Builder which will never get cleared, potentially creating a memory leak.
I'd suggest calling the static method RegistrationBuilder.ForType instead, which will give you a fluent builder and should let you subsequently call CreateRegistration as you are now.
You can see some pretty good examples of how do this in our Moq integration:
var reg = RegistrationBuilder.ForType(concrete)
.As(#interface)
.CreateRegistration();
Also, I don't believe IfNotRegistered will have any effect when used outside the context of a ContainerBuilder. You should use the provided registrationAccessor parameter to the registration source to look up a TypedService to see if it has already been registered:
var isRegistered = registrationAccessor(new TypedService(#interface)).Any();
I updated an older android project from mvvmcross v2 to mvvmcross v3.
Got one more problem now.
The visibility doesn't work, its doing nothing.
Old solution looked like this (worked fine):
In Setup.cs
protected override IEnumerable<Type> ValueConverterHolders
{
get { return new[] { typeof(Converters) }; }
}
Converters.cs
using Cirrious.MvvmCross.Converters.Visibility;
namespace Test.Droid
{
public class Converters
{
public readonly MvxVisibilityConverter Visibility = new MvxVisibilityConverter();
}
}
Any .axml (change visibility of LinearLayout):
<LinearLayout style="#style/LinearLayoutSmall" local:MvxBind="{'Visibility':{'Path':'TestIsVisible','Converter':'Visibility'}}">
New solution (doesn't work):
In Setup.cs
protected override List<Type> ValueConverterHolders
{
get { return new List<Type> { typeof(Converters) }; }
}
Converters.cs
using Cirrious.MvvmCross.Plugins.Visibility;
namespace Test.Droid
{
public class Converters
{
public readonly MvxVisibilityValueConverter Visibility = new MvxVisibilityValueConverter();
}
}
Any .axml
<LinearLayout style="#style/LinearLayoutSmall" local:MvxBind="Visibility TestIsVisible, Converter=Visibility">
There's probably a problem with the swissbinding syntax or I'm using false classes?
Any help appreciated!
UPDATE
I forgot these lines:
public override void LoadPlugins(IMvxPluginManager pluginManager)
{
pluginManager.EnsurePluginLoaded<PluginLoader>();
pluginManager.EnsurePluginLoaded<Cirrious.MvvmCross.Plugins.Visibility.PluginLoader>();
base.LoadPlugins(pluginManager);
}
I guess its necessary but now I'm having following error:
(from the MvxPluginManager Class)...
I checked all references and the dll/project *.Visibility.Droid.dll is referenced in my mainproject and everywhere else...
Without running and debugging a complete sample of your code I can't see what the problem is. One guess is that it could be in the plugin setup for visibility, but that is only a guess. The debug trace for your app might reveal some information on this.
Alternatively, it might be easier to simply try setting up a new project and getting visibility working in that, then comparing that code back to your existing app.
Value Converters in v3 are documented in https://github.com/MvvmCross/MvvmCross/wiki/Value-Converters.
The preferred way of referencing them is simply to let MvvmCross find them by reflection - see the section on https://github.com/MvvmCross/MvvmCross/wiki/Value-Converters#referencing-value-converters-in-touch-and-droid
A sample app, including visibility, is in: https://github.com/MvvmCross/MvvmCross-Tutorials/tree/master/ValueConversion - e.g. https://github.com/MvvmCross/MvvmCross-Tutorials/blob/master/ValueConversion/ValueConversion.UI.Droid/Resources/Layout/View_Visibility.axml
I have this really basic code in a MVC controller action. It maps an Operation model class to a very basic OperationVM view-model class .
public class OperationVM: Operation
{
public CategoryVM CategoryVM { get; set; }
}
I need to load the complete list of categories in order to create a CategoryVM instance.
Here's how I (try to) create a List<OperationVM> to show in the view.
public class OperationsController : Controller {
private SomeContext context = new SomeContext ();
public ViewResult Index()
{
var ops = context.Operations.Include("blah...").ToList();
Mapper.CreateMap<Operation, OperationVM>()
.ForMember(
dest => dest.CategoryVM,
opt => opt.MapFrom(
src => CreateCatVM(src.Category, context.Categories)
// trouble here ----------------^^^^^^^
)
);
var opVMs = ops.Select(op => Mapper.Map<Operation, OperationVM>(op))
.ToList();
return View(opVMs);
}
}
All works great first time I hit the page. The problem is, the mapper object is static. So when calling Mapper.CreateMap(), the instance of the current DbContext is saved in the closure given to CreateMap().
The 2nd time I hit the page, the static map is already in place, still using the reference to the initial, now disposed, DbContext.
The exact error is:
The operation cannot be completed because the DbContext has been disposed.
The question is: How can I make AutoMapper always use the current context instead of the initial one?
Is there a way to use an "instance" of automapper instead of the static Mapper class?
If this is possible, is it recommended to re-create the mapping every time? I'm worried about reflection slow-downs.
I read a bit about custom resolvers, but I get a similar problem - How do I get the custom resolver to use the current context?
It is possible, but the setup is a bit complicated. I use this in my projects with help of Ninject for dependency injection.
AutoMapper has concept of TypeConverters. Converters provide a way to implement complex operations required to convert certain types in a separate class. If converting Category to CategoryVM requires a database lookup you can implement that logic in custom TypeConverter class similar to this:
using System;
using AutoMapper;
public class CategoryToCategoryVMConverter :
TypeConverter<Category, CategoryVM>
{
public CategoryToCategoryVMConverter(DbContext context)
{
this.Context = context;
}
private DbContext Context { get; set; }
protected override CategoryVM ConvertCore(Category source)
{
// use this.Context to lookup whatever you need
return CreateCatVM(source, this.Context.Categories);
}
}
You then to configure AutoMapper to use your converter:
Mapper.CreateMap<Category, CategoryVM>().ConvertUsing<CategoryToCategoryVMConverter>();
Here comes the tricky part. AutoMapper will need to create a new instance of our converter every time you map values, and it will need to provide DbContext instance for constructor. In my projects I use Ninject for dependency injection, and it is configured to use the same instance of DbContext while processing a request. This way the same instance of DbContext is injected both in your controller and in your AutoMapper converter. The trivial Ninject configuration would look like this:
Bind<DbContext>().To<SomeContext>().InRequestScope();
You can of course use some sort of factory pattern to get instance of DbContext instead of injecting it in constructors.
Let me know if you have any questions.
I've found a workaround that's not completely hacky.
Basically, I tell AutoMapper to ignore the tricky field and I update it myself.
The updated controller looks like this:
public class OperationsController : Controller {
private SomeContext context = new SomeContext ();
public ViewResult Index()
{
var ops = context.Operations.Include("blah...").ToList();
Mapper.CreateMap<Operation, OperationVM>()
.ForMember(dest => dest.CategoryVM, opt => opt.Ignore());
var opVMs = ops.Select(
op => {
var opVM = Mapper.Map<Operation, OperationVM>(op);
opVM.CategoryVM = CreateCatVM(op.Category, context.Categories);
return opVM;
})
.ToList();
return View(opVMs);
}
}
Still curious how this could be done from within AutoMapper...
The answer from #LeffeBrune is perfect. However, I want to have the same behavior, but I don't want to map every property myself. Basically I just wanted to override the "ConstructUsing".
Here is what I came up with.
public static class AutoMapperExtension
{
public static void ConstructUsingService<TSource, TDestination>(this IMappingExpression<TSource, TDestination> mappingExression, Type typeConverterType)
{
mappingExression.ConstructUsing((ResolutionContext ctx) =>
{
var constructor = (IConstructorWithService<TSource, TDestination>)ctx.Options.ServiceCtor.Invoke(typeConverterType);
return constructor.Construct((TSource)ctx.SourceValue);
});
}
}
public class CategoryToCategoryVMConstructor : IConstructorWithService<Category, CategoryVM>
{
private DbContext dbContext;
public DTOSiteToHBTISiteConverter(DbContext dbContext)
{
this.dbContext = dbContext;
}
public CategoryVM Construct(Category category)
{
// Some commands here
if (category.Id > 0)
{
var vmCategory = dbContext.Categories.FirstOrDefault(m => m.Id == category.Id);
if (vmCategory == null)
{
throw new NotAllowedException();
}
return vmCategory;
}
return new CategoryVM();
}
}
// Initialization
Mapper.Initialize(cfg =>
{
cfg.ConstructServicesUsing(type => nInjectKernelForInstance.Get(type));
cfg.CreateMap<Category, CategoryVM>().ConstructUsingService(typeof(CategoryToCategoryVMConstructor));
};
When I run following code:
public ActionResult Complete()
{
try
{
VeriTabanDataContext db = new VeriTabanDataContext();
db.Persons.InsertOnSubmit(_person);
db.SubmitChanges();
return View(_person);
}
catch (Exception ex)
{
return RedirectToAction("Error", ex);
}
}
I'm getting following Exception, on SubmitChanges();
"An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported."
Here "_person" object is taken from Session and is a good standing. Note: _person is a result of multistep wizard and this is the place where I add new Person object to the DB.
My Person table has 9 relations and it's not ok for me to add version column for each of them as is suggested by some geeks around
I've investigated this problem a lot and spend 2 days on it and still couldn't solve it. Some of the workarounds that other suggest don't solve my problem, and others seem to be just dirty workaround. Do you experts have a good solution for this problem, considering that Person class has many relations and also it isn't ok to add a column to the tables.
I also want to note that I've tried to use 'db.Persons.Attach(_person) ' and setting db.DeferredLoadingEnabled = false; THis time I'm not getting any Exception but data is NOT saved to DB
I create a class called applicationController which derives from Controller. Then i make all of my controller classes derive from this. The applicationController class has a constrcutor which creates a new instance of my repository (or datacontext in your instance) which is used throughout the application:
public class ApplicationController : Controller
{
private VeriTabanDataContext _datacontext;
public ApplicationController() : this(new VeriTabanDataContext())
{
}
public ApplicationController(VeriTabanDataContext datacontext)
{
_datacontext = datacontext;
}
Public VeriTabanDataContext DataContext
{
get { return _datacontext; }
}
}
Then you can use this in all of your controllers
public class MyController : ApplicationController
{
public ActionResult Complete()
{
DataContext.Persons.InsertOnSubmit(_person);
DataContext.SubmitChanges();
return View(_person);
}
}
Not on my PC with VS installed at the moment so not tested this code....
Hope this resolves the issue -Mark
Can you do the following:
var foundPerson = db.Person.FirstOrDefault( p => p.Id == _person.Id);
if(foundPerson == null)
{
db.InsertOnSubmit(_person);
}else{
Mapper.Map(_person,foundPerson);
}
db.SubmitChanges();
return View(_person);
Where I have used AutoMapper to map from one entity to another. To do this add the reference to AutoMapper to your project and in your start up code for the application you will need to configure your mappings, for the above to work you would need:
Mapper.CreateMap<Person, Person>().ForMember(src => src.Id, opt => opt.Ignore());
I'm trying to implement my own GenericIdentity implementation but keep receiving the following error when it attempts to load the views (I'm using asp.net MVC):
System.Runtime.Serialization.SerializationException was unhandled
by user code Message="Type is not resolved for member
'OpenIDExtendedIdentity,Training.Web, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null'."
Source="WebDev.WebHost"
I've ended up with the following class:
[Serializable]
public class OpenIDExtendedIdentity : GenericIdentity {
private string _nickName;
private int _userId;
public OpenIDExtendedIdentity(String name, string nickName, int userId)
: base(name, "OpenID") {
_nickName = nickName;
_userId = userId;
}
public string NickName {
get { return _nickName; }
}
public int UserID {
get { return _userId; }
}
}
In my Global.asax I read a cookie's serialized value into a memory stream and then use that to create my OpenIDExtendedIdentity object. I ended up with this attempt at a solution after countless tries of various sorts. It works correctly up until the point where it attempts to render the views.
What I'm essentially attempting to achieve is the ability to do the following (While using the default Role manager from asp.net):
User.Identity.UserID
User.Identity.NickName
... etc.
I've listed some of the sources I've read in my attempt to get this resolved. Some people have reported a Cassini error, but it seems like others have had success implementing this type of custom functionality - thus a boggling of my mind.
http://forums.asp.net/p/32497/161775.aspx
http://ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html
http://social.msdn.microsoft.com/Forums/en-US/netfxremoting/thread/e6767ae2-dfbf-445b-9139-93735f1a0f72
I'm not sure if this is exactly the same issue, but I've run into the same issue when trying to create my own identity implementation.
This blog solved my problem.
It seems that the problem is there's an issue with identity serialization in Cassini, but you can get around it by deriving your class from MarshalByRefObject:
[Serializable]
public class MyUser : MarshalByRefObject, IIdentity
{
public int UserId ...
You can't inherit from GenericIdentity then, of course, but you can still implement the IIdentity interface that GenericIdentity implements, so you can use the thing in most places that expect an IIdentity at least.
It seems to be a limitation or a bug of the VisualStudio (Web Development Server), when I used the IIS Express in VS2012 or the full IIS config, the problem was fixed. Like suggested here: https://stackoverflow.com/a/1287129/926064
Solution from "baggadonuts" at This post solved my problem. Copied code below.
[Serializable]
public class StubIdentity : IIdentity, ISerializable
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (context.State == StreamingContextStates.CrossAppDomain)
{
GenericIdentity gIdent = new GenericIdentity(this.Name, this.AuthenticationType);
info.SetType(gIdent.GetType());
System.Reflection.MemberInfo[] serializableMembers;
object[] serializableValues;
serializableMembers = FormatterServices.GetSerializableMembers(gIdent.GetType());
serializableValues = FormatterServices.GetObjectData(gIdent, serializableMembers);
for (int i = 0; i < serializableMembers.Length; i++)
{
info.AddValue(serializableMembers[i].Name, serializableValues[i]);
}
}
else
{
throw new InvalidOperationException("Serialization not supported");
}
}