Search Results

Search found 77 results on 4 pages for 'objectfactory'.

Page 1/4 | 1 2 3 4  | Next Page >

  • How to generate several versions of Java classes generated by JAXB ?

    - by mica16
    Hello, I recently generate two versions of Java classes generated by JAXB. So I get two packages : V1_0 and V2_0 I notice that I have only one ObjectFactory generated. The problem is that this ObjectFactory is specific to a version (here it's specific to my version v1_0). So the question is : Could I configure JAXB to allow to make one ObjectFactory for each version ? Thanks a lot.

    Read the article

  • StructureMap Configuration Per Thread/Request for the Full Dependency Chain

    - by Phil Sandler
    I've been using Structuremap for a few months now, and it has worked great on some smaller (green field) projects. Most of the configurations I have had to set up involve a single implementation per interface. In the cases where I needed to choose a specific implementation at runtime, I created a factory class that used ObjectFactory.GetNamedInstance<(). In the smaller projects, there were few enough of these cases where I was comfortable with the references to ObjectFactory. My understanding is that you want to limit these references as much as possible, and ideally only reference the ObjectFactory once. I am working to refactor a larger codebase to use IOC/StructureMap, and am finding that I may need many of these factory classes with ObjectFactory references to get what I need. Essentially, I am creating a "root service" with the ObjectFactory, so that everything in the dependency chain is managed by the container. The root service is created by name (i.e. "BuildCar", "BuildTruck"), and the services needed deeper in the dependency chain could also be constructed using the same name--so the "IAttachWheels" service could vary based on whether a car or truck is being built. Since the class that depends on IAttachWheels is the same in both configurations, I don't think I can use ConstructedBy in the registry to choose the implementation. Also, to be clear, the IAttachWheels implementations need to be managed by the container as well, because the dependency chain runs fairly deep. I looked briefly at Profiles as an option, but read (here on StackOverflow) that changing profiles essentially changes implementations for all threads. Is there a feature that is similar to profiles that is thread/request specific? Is the factory class that references ObjectFactory approach the right way to go? Any thoughts would be appreciated.

    Read the article

  • Using Factory to get Injected objects

    - by ryudice
    Is it good practice to have a Factory method to retrieve injected objects or is it OK to just use the factory method from the DI framework? I'm using structure map, should I just use ObjectFactory.GetInstance();, or should I create factory class and inside this class call ObjectFactory.GetInstance();? because if I call ObjectFactory.GetInstance(); in my classes I would be creating coupling to the DI framework? sorry if I'm being ignorant, I'm new to this concepts. Thanks!

    Read the article

  • How to use StructureMap to inject repository classes to the controller?

    - by Lorenzo
    In the current application I am working on I have a custom ControllerFactory class that create a controller and automatically sets the Elmah ErrorHandler. public class BaseControllerFactory : DefaultControllerFactory { public override IController CreateController( RequestContext requestContext, string controllerName ) { var controller = base.CreateController( requestContext, controllerName ); var c = controller as Controller; if ( c != null ) { c.ActionInvoker = new ErrorHandlingActionInvoker( new HandleErrorWithElmahAttribute() ); } return controller; } protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType ) { try { if ( ( requestContext == null ) || ( controllerType == null ) ) return base.GetControllerInstance( requestContext, controllerType ); return (Controller)ObjectFactory.GetInstance( controllerType ); } catch ( StructureMapException ) { System.Diagnostics.Debug.WriteLine( ObjectFactory.WhatDoIHave() ); throw new Exception( ObjectFactory.WhatDoIHave() ); } } } I would like to use StructureMap to inject some code in my controllers. For example I would like to automatically inject repository classes in them. I have already created my repository classes and also I have added a constructor to the controller that receive the repository class public FirmController( IContactRepository contactRepository ) { _contactRepository = contactRepository; } I have then registered the type within StructureMap ObjectFactory.Initialize( x => { x.For<IContactRepository>().Use<MyContactRepository>(); }); How should I change the code in the CreateController method to have the IContactRepository concrete class injected in the FirmController? EDIT: I have changed the BaseControllerFactory to use Structuremap. But I get an exception on the line return (Controller)ObjectFactory.GetInstance( controllerType ); Any hint?

    Read the article

  • Generating Java classes out of XMLSchema.xsd using JAXB

    - by Christian Schulz
    I'm using jaxb to generate java classes out of a xml schema. The schema imports XMLSchema.xsd and its content is used as an element in the document. If I remove the import and the reference to "xsd:schema" respectively then the binding compiler generates successfully the classes. If I do not then it would produce the following errors, which are the same if I would try to generate Java classes from the XMLSchema.xsd only! C:\Users\me"%JAXB%/xjc" -extension -d tmp/uisocketdesc -p uis.jaxb uisocketdesc.xsd -b xml_binding_test.xml -b xml_binding_test_2.xml -b xml_binding_test_3.xml parsing a schema... compiling a schema... [ERROR] A class/interface with the same name "uis.jaxb.ComplexType" is already in use. Use a class customization to resolve this conflict. line 612 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Relevant to above error) another "ComplexType" is generated from here. line 440 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] A class/interface with the same name "uis.jaxb.Attribute" is already in use. Use a class customization to resolve this conflict. line 364 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Relevant to above error) another "Attribute" is generated from here. line 1020 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] A class/interface with the same name "uis.jaxb.SimpleType" is already in use. Use a class customization to resolve this conflict. line 2278 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Relevant to above error) another "SimpleType" is generated from here. line 2222 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] A class/interface with the same name "uis.jaxb.Group" is already in use. Use a class customization to resolve this conflict. line 930 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Relevant to above error) another "Group" is generated from here. line 727 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] A class/interface with the same name "uis.jaxb.AttributeGroup" is already in use. Use a class customization to resolve this conflict. line 1062 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Relevant to above error) another "AttributeGroup" is generated from here. line 1026 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] A class/interface with the same name "uis.jaxb.Element" is already in use. Use a class customization to resolve this conflict. line 721 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Relevant to above error) another "Element" is generated from here. line 647 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] Two declarations cause a collision in the ObjectFactory class. line 1020 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Related to above error) This is the other declaration. line 364 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] Two declarations cause a collision in the ObjectFactory class. line 2278 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Related to above error) This is the other declaration. line 2222 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] Two declarations cause a collision in the ObjectFactory class. line 930 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Related to above error) This is the other declaration. line 727 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] Two declarations cause a collision in the ObjectFactory class. line 440 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Related to above error) This is the other declaration. line 612 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] Two declarations cause a collision in the ObjectFactory class. line 1026 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Related to above error) This is the other declaration. line 1062 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] Two declarations cause a collision in the ObjectFactory class. line 647 of "http://www.w3.org/2001/XMLSchema.xsd" [ERROR] (Related to above error) This is the other declaration. line 721 of "http://www.w3.org/2001/XMLSchema.xsd" Failed to produce code.

    Read the article

  • Loading a Template From a User Control

    - by Ricardo Peres
    What if you wanted to load a template (ITemplate property) from an external user control (.ascx) file? Yes, it is possible; there are a number of ways to do this, the one I'll talk about here is through a type converter. You need to apply a TypeConverterAttribute to your ITemplate property where you specify a custom type converter that does the job. This type converter relies on InstanceDescriptor. Here is the code for it: public class TemplateTypeConverter: TypeConverter { public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return ((sourceType == typeof(String)) || (base.CanConvertFrom(context, sourceType) == true)); } public override Boolean CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return ((destinationType == typeof(InstanceDescriptor)) || (base.CanConvertTo(context, destinationType) == true)); } public override Object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { Object objectFactory = value.GetType().GetField("_objectFactory", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(value); Object builtType = objectFactory.GetType().BaseType.GetField("_builtType", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectFactory); MethodInfo loadTemplate = typeof(TemplateTypeConverter).GetMethod("LoadTemplate"); return (new InstanceDescriptor(loadTemplate, new Object [] { "~/" + (builtType as Type).Name.Replace('_', '/').Replace("/ascx", ".ascx") })); } return base.ConvertTo(context, culture, value, destinationType); } public static ITemplate LoadTemplate(String virtualPath) { using (Page page = new Page()) { return (page.LoadTemplate(virtualPath)); } } } And, on your control: public class MyControl: Control { [Browsable(false)] [TypeConverter(typeof(TemplateTypeConverter))] public ITemplate Template { get; set; } } This allows the following declaration: Hope this helps! SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.brushes.Xml.aliases = ['xml']; SyntaxHighlighter.all();

    Read the article

  • Jaxb2Marshaller and primitive types

    - by Thomas Einwaller
    Is it possible to create a web service operation using primitive or basic Java types when using the Jaxb2Marschaller in spring-ws? For example a method looking like this: @Override @PayloadRoot(localPart = "AddTaskRequest", namespace = "http://example.com/examplews/") public long addTask(final Task task) throws AddTaskFault { // do something return 0; } I am using the maven jaxws plugin to generate the interface and model classes from my WSDL. When I try to call the webservice I get the following error: java.lang.IllegalStateException: No adapter for endpoint [...]: Does your endpoint implement a supported interface like MessageHandler or PayloadEndpoint I found out that if I change the method to that: @Override @PayloadRoot(localPart = "AddTaskRequest", namespace = "http://example.com/examplews/") public JAXBElement<Long> addTask(final JAXBElement<Task> task) throws AddTaskFault { final ObjectFactory objectFactory = new ObjectFactory(); return objectFactory.createAddTaskResponse(0L); } I am able to call it - but this signature is not compatible with the interface generated by the maven jaxws plugin. What can I do to configure either spring-ws to be able to use the first kind of implementation or to tell maven jaxws plugin to generate the second variant of the interface? UPDATE: My relevant spring-ws config entries look like that: <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> <property name="contextPath" value="com.example.examplews" /> </bean> <bean class="org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter"> <constructor-arg ref="marshaller" /> </bean> <bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping"> <property name="order" value="1" /> </bean>

    Read the article

  • Single website multiple connection strings using asp mvc 2 and nhibernate

    - by jjjjj
    Hi In my website i use ASP MVC 2 + Fluent NHibernate as orm, StructureMap for IoC container. There are several databases with identical metadata(and so entities and mappings are the same). On LogOn page user fiils in login, password, rememberme and chooses his server from dropdownlist (in fact he chooses database). Web.config contains all connstrings and we can assume that they won't be changed in run-time. I suppose that it is required to have one session factory per database. Before using multiple databases, i loaded classes to my StructureMap ObjectFactory in Application_Start ObjectFactory.Initialize(init => init.AddRegistry<ObjectRegistry>()); ObjectFactory.Configure(conf => conf.AddRegistry<NhibernateRegistry>()); NhibernateRegistry class: public class NhibernateRegistry : Registry { public NhibernateRegistry() { var sessionFactory = NhibernateConfiguration.Configuration.BuildSessionFactory(); For<Configuration>().Singleton().Use( NhibernateConfiguration.Configuration); For<ISessionFactory>().Singleton().Use(sessionFactory); For<ISession>().HybridHttpOrThreadLocalScoped().Use( ctx => ctx.GetInstance<ISessionFactory>().GetCurrentSession()); } } In Application_BeginRequest i bind opened nhibernate session to asp session(nhibernate session per request) and in EndRequest i unbind them: protected void Application_BeginRequest( object sender, EventArgs e) { CurrentSessionContext.Bind(ObjectFactory.GetInstance<ISessionFactory>().OpenSession()); } Q1: How can i realize what SessionFactory should i use according to authenticated user? is it something like UserData filled with database name (i use simple FormsAuthentication) For logging i use log4net, namely AdoNetAppender which contains connectionString(in xml, of course). Q2: How can i manage multiple connection strings for this database appender, so logs would be written to current database? I have no idea how to do that except changing xml all the time and reseting xml configuration, but its really bad solution.

    Read the article

  • Context problem while loading Assemblies via Structuremap

    - by Zebi
    I want to load plugins in a smiliar way as shown here however the loaded assemblies seem not to share the same context. Trying to solve the problem I just build a tiny spike containing two assemblies. One console app and one library. The console app contains the IPlugin interface and has no references to the Plugin dll. I am scanning the plugin dir using a custom Registration convention: ObjectFactory.Initialize(x => x.Scan(s => { s.AssembliesFromPath(@"..\Plugin"); s.With(new PluginScanner()); })); public void Process(Type type, Registry registry) { if (!type.Name.StartsWith("P")) return; var instance = ObjectFactory.GetInstance(type); registry.For<IPlugin>().Add((IPlugin)instance); } Which thows an invalid cast exception saying he can not convert the plugin Type to IPlugin. public class P1 : IPlugin { public void Start() { Console.WriteLine("Hello from P1"); } } Further if I just construct the instance (which works fine by the way) and try to access ObjectFactory in the plugin ObjectFactory.WhatDoIHave() shows that they don't even share the same container instance. Experimenting around with MEF, Structuremap and loading the assembly manually whith Assembly.Load("Plugin") shows if loaded with Assembly.Load it works fine. Any ideas how I can fix this to work with StructureMaps assembly scanning?

    Read the article

  • Using TPL and PLINQ to raise performance of feed aggregator

    - by DigiMortal
    In this posting I will show you how to use Task Parallel Library (TPL) and PLINQ features to boost performance of simple RSS-feed aggregator. I will use here only very basic .NET classes that almost every developer starts from when learning parallel programming. Of course, we will also measure how every optimization affects performance of feed aggregator. Feed aggregator Our feed aggregator works as follows: Load list of blogs Download RSS-feed Parse feed XML Add new posts to database Our feed aggregator is run by task scheduler after every 15 minutes by example. We will start our journey with serial implementation of feed aggregator. Second step is to use task parallelism and parallelize feeds downloading and parsing. And our last step is to use data parallelism to parallelize database operations. We will use Stopwatch class to measure how much time it takes for aggregator to download and insert all posts from all registered blogs. After every run we empty posts table in database. Serial aggregation Before doing parallel stuff let’s take a look at serial implementation of feed aggregator. All tasks happen one after other. internal class FeedClient {     private readonly INewsService _newsService;     private const int FeedItemContentMaxLength = 255;       public FeedClient()     {          ObjectFactory.Initialize(container =>          {              container.PullConfigurationFromAppConfig = true;          });           _newsService = ObjectFactory.GetInstance<INewsService>();     }       public void Execute()     {         var blogs = _newsService.ListPublishedBlogs();           for (var index = 0; index <blogs.Count; index++)         {              ImportFeed(blogs[index]);         }     }       private void ImportFeed(BlogDto blog)     {         if(blog == null)             return;         if (string.IsNullOrEmpty(blog.RssUrl))             return;           var uri = new Uri(blog.RssUrl);         SyndicationContentFormat feedFormat;           feedFormat = SyndicationDiscoveryUtility.SyndicationContentFormatGet(uri);           if (feedFormat == SyndicationContentFormat.Rss)             ImportRssFeed(blog);         if (feedFormat == SyndicationContentFormat.Atom)             ImportAtomFeed(blog);                 }       private void ImportRssFeed(BlogDto blog)     {         var uri = new Uri(blog.RssUrl);         var feed = RssFeed.Create(uri);           foreach (var item in feed.Channel.Items)         {             SaveRssFeedItem(item, blog.Id, blog.CreatedById);         }     }       private void ImportAtomFeed(BlogDto blog)     {         var uri = new Uri(blog.RssUrl);         var feed = AtomFeed.Create(uri);           foreach (var item in feed.Entries)         {             SaveAtomFeedEntry(item, blog.Id, blog.CreatedById);         }     } } Serial implementation of feed aggregator downloads and inserts all posts with 25.46 seconds. Task parallelism Task parallelism means that separate tasks are run in parallel. You can find out more about task parallelism from MSDN page Task Parallelism (Task Parallel Library) and Wikipedia page Task parallelism. Although finding parts of code that can run safely in parallel without synchronization issues is not easy task we are lucky this time. Feeds import and parsing is perfect candidate for parallel tasks. We can safely parallelize feeds import because importing tasks doesn’t share any resources and therefore they don’t also need any synchronization. After getting the list of blogs we iterate through the collection and start new TPL task for each blog feed aggregation. internal class FeedClient {     private readonly INewsService _newsService;     private const int FeedItemContentMaxLength = 255;       public FeedClient()     {          ObjectFactory.Initialize(container =>          {              container.PullConfigurationFromAppConfig = true;          });           _newsService = ObjectFactory.GetInstance<INewsService>();     }       public void Execute()     {         var blogs = _newsService.ListPublishedBlogs();                var tasks = new Task[blogs.Count];           for (var index = 0; index <blogs.Count; index++)         {             tasks[index] = new Task(ImportFeed, blogs[index]);             tasks[index].Start();         }           Task.WaitAll(tasks);     }       private void ImportFeed(object blogObject)     {         if(blogObject == null)             return;         var blog = (BlogDto)blogObject;         if (string.IsNullOrEmpty(blog.RssUrl))             return;           var uri = new Uri(blog.RssUrl);         SyndicationContentFormat feedFormat;           feedFormat = SyndicationDiscoveryUtility.SyndicationContentFormatGet(uri);           if (feedFormat == SyndicationContentFormat.Rss)             ImportRssFeed(blog);         if (feedFormat == SyndicationContentFormat.Atom)             ImportAtomFeed(blog);                }       private void ImportRssFeed(BlogDto blog)     {          var uri = new Uri(blog.RssUrl);          var feed = RssFeed.Create(uri);           foreach (var item in feed.Channel.Items)          {              SaveRssFeedItem(item, blog.Id, blog.CreatedById);          }     }     private void ImportAtomFeed(BlogDto blog)     {         var uri = new Uri(blog.RssUrl);         var feed = AtomFeed.Create(uri);           foreach (var item in feed.Entries)         {             SaveAtomFeedEntry(item, blog.Id, blog.CreatedById);         }     } } You should notice first signs of the power of TPL. We made only minor changes to our code to parallelize blog feeds aggregating. On my machine this modification gives some performance boost – time is now 17.57 seconds. Data parallelism There is one more way how to parallelize activities. Previous section introduced task or operation based parallelism, this section introduces data based parallelism. By MSDN page Data Parallelism (Task Parallel Library) data parallelism refers to scenario in which the same operation is performed concurrently on elements in a source collection or array. In our code we have independent collections we can process in parallel – imported feed entries. As checking for feed entry existence and inserting it if it is missing from database doesn’t affect other entries the imported feed entries collection is ideal candidate for parallelization. internal class FeedClient {     private readonly INewsService _newsService;     private const int FeedItemContentMaxLength = 255;       public FeedClient()     {          ObjectFactory.Initialize(container =>          {              container.PullConfigurationFromAppConfig = true;          });           _newsService = ObjectFactory.GetInstance<INewsService>();     }       public void Execute()     {         var blogs = _newsService.ListPublishedBlogs();                var tasks = new Task[blogs.Count];           for (var index = 0; index <blogs.Count; index++)         {             tasks[index] = new Task(ImportFeed, blogs[index]);             tasks[index].Start();         }           Task.WaitAll(tasks);     }       private void ImportFeed(object blogObject)     {         if(blogObject == null)             return;         var blog = (BlogDto)blogObject;         if (string.IsNullOrEmpty(blog.RssUrl))             return;           var uri = new Uri(blog.RssUrl);         SyndicationContentFormat feedFormat;           feedFormat = SyndicationDiscoveryUtility.SyndicationContentFormatGet(uri);           if (feedFormat == SyndicationContentFormat.Rss)             ImportRssFeed(blog);         if (feedFormat == SyndicationContentFormat.Atom)             ImportAtomFeed(blog);                }       private void ImportRssFeed(BlogDto blog)     {         var uri = new Uri(blog.RssUrl);         var feed = RssFeed.Create(uri);           feed.Channel.Items.AsParallel().ForAll(a =>         {             SaveRssFeedItem(a, blog.Id, blog.CreatedById);         });      }        private void ImportAtomFeed(BlogDto blog)      {         var uri = new Uri(blog.RssUrl);         var feed = AtomFeed.Create(uri);           feed.Entries.AsParallel().ForAll(a =>         {              SaveAtomFeedEntry(a, blog.Id, blog.CreatedById);         });      } } We did small change again and as the result we parallelized checking and saving of feed items. This change was data centric as we applied same operation to all elements in collection. On my machine I got better performance again. Time is now 11.22 seconds. Results Let’s visualize our measurement results (numbers are given in seconds). As we can see then with task parallelism feed aggregation takes about 25% less time than in original case. When adding data parallelism to task parallelism our aggregation takes about 2.3 times less time than in original case. More about TPL and PLINQ Adding parallelism to your application can be very challenging task. You have to carefully find out parts of your code where you can safely go to parallel processing and even then you have to measure the effects of parallel processing to find out if parallel code performs better. If you are not careful then troubles you will face later are worse than ones you have seen before (imagine error that occurs by average only once per 10000 code runs). Parallel programming is something that is hard to ignore. Effective programs are able to use multiple cores of processors. Using TPL you can also set degree of parallelism so your application doesn’t use all computing cores and leaves one or more of them free for host system and other processes. And there are many more things in TPL that make it easier for you to start and go on with parallel programming. In next major version all .NET languages will have built-in support for parallel programming. There will be also new language constructs that support parallel programming. Currently you can download Visual Studio Async to get some idea about what is coming. Conclusion Parallel programming is very challenging but good tools offered by Visual Studio and .NET Framework make it way easier for us. In this posting we started with feed aggregator that imports feed items on serial mode. With two steps we parallelized feed importing and entries inserting gaining 2.3 times raise in performance. Although this number is specific to my test environment it shows clearly that parallel programming may raise the performance of your application significantly.

    Read the article

  • Opengl-es picking object

    - by lacas
    I saw a lot of picking code opengl-es, but nothing worked. Can someone give me what am I missing? My code is (from tutorials/forums) Vec3 far = Camera.getPosition(); Vec3 near = Shared.opengl().getPickingRay(ev.getX(), ev.getY(), 0); Vec3 direction = far.sub(near); direction.normalize(); Log.e("direction", direction.x+" "+direction.y+" "+direction.z); Ray mouseRay = new Ray(near, direction); for (int n=0; n<ObjectFactory.objects.size(); n++) { if (ObjectFactory.objects.get(n)!=null) { IObject obj = ObjectFactory.objects.get(n); float discriminant, b; float radius=0.1f; b = -mouseRay.getOrigin().dot(mouseRay.getDirection()); discriminant = b * b - mouseRay.getOrigin().dot(mouseRay.getOrigin()) + radius*radius; discriminant = FloatMath.sqrt(discriminant); double x1 = b - discriminant; double x2 = b + discriminant; Log.e("asd", obj.getName() + " "+discriminant+" "+x1+" "+x2); } } my camera vectors: //cam Vec3 position =new Vec3(-obj.getPosX()+x, obj.getPosZ()-0.3f, obj.getPosY()+z); Vec3 direction =new Vec3(-obj.getPosX(), obj.getPosZ(), obj.getPosY()); Vec3 up =new Vec3(0.0f, -1.0f, 0.0f); Camera.set(position, direction, up); and my picking code: public Vec3 getPickingRay(float mouseX, float mouseY, float mouseZ) { int[] viewport = getViewport(); float[] modelview = getModelView(); float[] projection = getProjection(); float winX, winY; float[] position = new float[4]; winX = (float)mouseX; winY = (float)Shared.screen.width - (float)mouseY; GLU.gluUnProject(winX, winY, mouseZ, modelview, 0, projection, 0, viewport, 0, position, 0); return new Vec3(position[0], position[1], position[2]); } My camera moving all the time in 3d space. and my actors/modells moving too. my camera is following one actor/modell and the user can move the camera on a circle on this model. How can I change the above code to working?

    Read the article

  • Get a new instance with StructureMap

    - by Aligned
    It took me too long to figure this out, so hopefully it will help you. StructureMap has way that will create a new instance of the object every time, instead of storing this in the container. I’m going to use this for the DBContext and for WCF Service references. Since the ObjectFactory is a static class, MVC will have these stored in memory without this. Credit goes to Joshua Flanagan for answering my question.[TestMethod] public void GetConcreteInstanceOf_ShouldReturn_DifferentInstance() { ObjectFactory.Initialize(registry => { // set it up so that it's new every time // use this for DBContext and service references registry.For<ISystemDataService>().Use(() => new SystemDataService()); }); ISystemDataService result = Resolver.GetConcreteInstanceOf<ISystemDataService>(); ISystemDataService result2 = Resolver.GetConcreteInstanceOf<ISystemDataService>(); Assert.AreNotSame(result, result2); }

    Read the article

  • How to setup named instances using StructureMap profiles?

    - by khaledh
    I've done quite a bit of googling and searching here on SO, but couldn't find a similar question or answer. In typical SM configuration you can add multiple named instances for a single PluginType: ForRequestedType<IFoo>() .AddInstances( x => { x.OfConcreteType<FooA>().WithName( "FooA" ); x.OfConcreteType<FooB>().WithName( "FooB" ); } ); No problem there. The problem is that I can't do the same when creating a profile. Most examples explaining how to use profiles use the For<>() method of the passed ProfileExpression: CreateProfile( "Default", p => { p.For<IFoo>().UseConcreteType<FooC>(); } ); I can't seem to find a way to add multiple named instances for the same PluginType as you can do above with regular configuration. The only other method available through ProfileExpression is Type<>(), but I'm not sure if it can be used for this purpose. Edit: I tried to use Type<>() instead of For<>() and it seems to be taking me in the right direction, but I bumped into another problem. To better explain it here's a better example of what I'm trying to do (this is what I posted to the structuremap-users group, no answer yet): ObjectFactory.Initialize( x => { x.CreateProfile( "Nissan", p => { p.Type<ICar>().Is.OfConcreteType<NewNissanCar>().WithName( "New" ); p.Type<ICar>().Is.OfConcreteType<OldNissanCar>().WithName( "Old" ); } ); x.CreateProfile( "Honda", p => { p.Type<ICar>().Is.OfConcreteType<NewHondaCar>().WithName( "New" ); p.Type<ICar>().Is.OfConcreteType<OldHondaCar>().WithName( "Old" ); } ); } ); ObjectFactory.Profile = "Nissan"; ICar newCar = ObjectFactory.GetNamedInstance<ICar>( "New" ); // -> returns NewHondaCar ICar car = ObjectFactory.GetInstance<ICar>(); // -> returns OldNissanCar So even though I set the profile to "Nissan", GetNamedInstance<>("New") returned an instance from the incorrect profile - it should've returned NewNissanCar instead of NewHondaCar. Interestingly, GetInstance<>() uses the correct profile, but because I can't pass an instance name, it returns an arbitrary concrete type from that profile that implements ICar (I guess it just returns the last concrete type added for that interface).

    Read the article

  • StructureMap Autowiring with two different instances of the same interface

    - by Lambda
    For the last two days, i tried my best to learn something about StructureMap, using an old project of mine as an concrete implementation example. I tried to simplify my question as much as possible. While i will post my examples in vb.net, answers with examples in C# are also okay. The project includes an interfaces called IDatabase which connects itself to a Database. The important part looks like this. Public Interface IDatabase Function Connect(ByVal ConnectionSettings As ConnectionSettings) As Boolean ReadOnly Property ConnectionOpen As Boolean [... more functions...] End Interface Public Class MSSQLConnection Implements IDatabase Public Function Connect(ByVal ConnectionSettings As ConnectionSettings) As Boolean Implements IDatabase.Connect [... Implementation ...] End Function [... more implementations...] End Class ConnectionSettings is a structure that has all the information needed to connect to a Database. I want to open the Database Connection once and use it for every single connection in the project, so i register a instance in the ObjectFactory. dim foo = ObjectFactory.GetInstance(Of MSSQLConnection)() dim bar as ConnectionSettings foo.connect(bar) ObjectFactory.Configure(Sub(x) x.For(Of IDatabase).Use(foo)) Up until this part, everything works like a charm. Now, i get to a point where i hav e classes that need an additional instance of IDatabase because they connect to a second database. Public Class ExampleClass Public Sub New(ByVal SameOldDatabase as IDatabase, ByVal NewDatabase as IDatabase) [...] Magic happens here [...] End Sub End Class I want this second IDatabase to behave much like the first one. I want it to use a concrete, single instance and want to connect it to a different database invoking Connect with a different ConnectionSettings. The problem is: While i'm pretty sure it's somewhow possible, (my initial idea was registering ExampleClass with alternative constructor arguments), i actually want to do it without registering ExampleClass. This probably involves more configuration, but i have no idea how to do it. So, basically, it comes down to this question: How do i configurate the ObjectFactory in a way that the autowiring always invokes the constructor with object Database1 for the first IDatabase parameter and object Database2 for the second one (if there is one?)

    Read the article

  • Problems integrating nServiceBus with StructureMap

    - by SimonB
    I'm trying to use StructureMap with nServiceBus. The Project: Uses a GenericHost Endpoint to send command messages Configures nServiceBus using the StructMapBuilder. Uses a simple StructureMap registry config Uses a start up class TestServer supporting IWantToRunAtStartup The TestServer class has ctor dependency on a TestManager class The TestManager class has ctor dependency on IBus ObjectFactory.WhatDoIHave() shows StructureMap knows how to construct the classes. When run I get buildup errors. nServiceBus seems to be overwriting the config? Note that when I add a IBus ctor depenendency to my event handlers without any other config all appears fine. Error: Exception when starting endpoint, error has been logged. Reason: Error creating object with name 'nSeviceBusStructureMapTest.TestServer' : Unsatisfied dependency expressed through constructor argument with index 0 of type [nSeviceBusStructureMapTest.ITestManager] : No unique object of type [nSeviceBusStructureMapTest.ITestManager] is defined : Unsatisfied dependency of type [nSeviceBusStructureMapTest.ITestManager]: expected at least 1 matching object to wire the [miningServiceManage] parameter on the constructor of object [nSeviceBusStructureMapTest.TestServer] Source: using System; using System.Diagnostics; using NServiceBus; using StructureMap; using StructureMap.Configuration.DSL; namespace nSeviceBusStructureMapTest { public class TestSmRegistry : Registry { public TestSmRegistry() { For<ITestManager>().Use<TestManager>(); For<TestServer>().Use<TestServer>(); } } public class TestEndPoint : AsA_Server, IConfigureThisEndpoint, IWantCustomLogging { public void Init() { Configure.With().StructureMapBuilder(ObjectFactory.Container); ObjectFactory.Configure(c => c.AddRegistry<TestSmRegistry>()); Debug.WriteLine(ObjectFactory.WhatDoIHave()); } } public class TestServer : IWantToRunAtStartup { public TestServer(ITestManager miningServiceManage) { _miningServiceManage = miningServiceManage; } private readonly ITestManager _miningServiceManage; public void Run() { _miningServiceManage.Run(); } public void Stop() { } } public interface ITestManager { void Run(); } public class TestManager : ITestManager { public TestManager(IBus bus) { _bus = bus; } private readonly IBus _bus; public void Run() { if (_bus == null) Debug.WriteLine("Error no bus"); // Send messages on bus; } } } <MsmqTransportConfig InputQueue="test" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" /> <UnicastBusConfig> <MessageEndpointMappings> </MessageEndpointMappings> </UnicastBusConfig> Any ideas?

    Read the article

  • Fluent API Style Usage

    - by Chris Dwyer
    When programming against a fluent API, I've seen the style mostly like this: var obj = objectFactory.CreateObject() .SetObjectParameter(paramName, value) .SetObjectParameter(paramName, value) .DoSomeTransformation(); What is the reasoning behind putting the dot at the beginning of the line instead of the end of the line like this: var obj = objectFactory.CreateObject(). SetObjectParameter(paramName, value). SetObjectParameter(paramName, value). DoSomeTransformation(); Or, is it merely a style thing that a team makes a consensus on?

    Read the article

  • web service - client classes

    - by Noona
    The web service that I implemented is up and running, when I try to run the client I get the following error with regard to the classes that were generated using wsimport, Caused by: java.security.PrivilegedActionException: com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 4 counts of IllegalAnnotationExceptions Two classes have the same XML type name "{http://server.agency.hw2/}userJoined". Use @XmlType.name and @XmlType.namespace to assign different names to them. this problem is related to the following location: at hw2.chat.backend.main.generatedfromserver.UserJoined at public javax.xml.bind.JAXBElement hw2.chat.backend.main.generatedfromserver.ObjectFactory.createUserJoined(hw2.chat.backend.main.generatedfromserver.UserJoined) at hw2.chat.backend.main.generatedfromserver.ObjectFactory this problem is related to the following location: at ChatCompany.BackendChatServer.hw2.chat.backend.main.generatedfromserver.UserJoined Two classes have the same XML type name "{http://server.agency.hw2/}userJoinedResponse". Use @XmlType.name and @XmlType.namespace to assign different names to them. this problem is related to the following location: at hw2.chat.backend.main.generatedfromserver.UserJoinedResponse at public javax.xml.bind.JAXBElement hw2.chat.backend.main.generatedfromserver.ObjectFactory.createUserJoinedResponse(hw2.chat.backend.main.generatedfromserver.UserJoinedResponse) But I can't figure out what exactly is meant by the error. I am assuming I need to change something in annotations in this class as pointed out by the compiler: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "userJoinedResponse") public class UserJoinedResponse { } could someone please point out why there's a name collision and what annotations I need to change? thanks

    Read the article

  • Can someone help me with this StructureMap error i'm getting?

    - by Pure.Krome
    Hi folks, I'm trying to wire up a simple ASP.NET MVC2 controller class to my own LoggingService. Code compiles fine, but I get the following runtime error :- {"StructureMap Exception Code: 202 No Default Instance defined for PluginFamily System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"} what the? mscorlib ???? Here's some sample code of my wiring up .. protected void Application_Start() { MvcHandler.DisableMvcResponseHeader = true; BootstrapStructureMap(); ControllerBuilder.Current.SetControllerFactory( new StructureMapControllerFactory()); RegisterRoutes(RouteTable.Routes); } private static void BootstrapStructureMap() { ObjectFactory.Initialize(x => x.For<ILoggingService>().Use<Log4NetLoggingService>()); } and finally the controller, simplified for this question ... public class SearchController : Controller { private readonly ILoggingService _log { get; set; } public SearchController(ILoggingService loggingService) : base(loggingService) { // Error checking removed for brevity. _log = loggingService; _log.Tag = "SearchController"; } ... } and the structuremap factory (main method), also way simplified for this question... protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { IController result = null; if (controllerType != null) { try { result = ObjectFactory.GetInstance(controllerType) as Controller; } catch (Exception exception) { if (exception is StructureMapException) { Debug.WriteLine(ObjectFactory.WhatDoIHave()); } } } } hmm. I just don't get it. StructureMap version 2.6.1.0 ASP.NET MVC 2. Any ideas?

    Read the article

  • StructureMap and injecting IEnumerable<T>

    - by GiddyUpHorsey
    I'm new to StructureMap and have some existing code that I'm working with that uses StructureMap 2.5.4. There is a class that is constructed using StructureMap that has a constructor that takes IEnumerable<TCar> as a parameter. The registry has the following code. Scan(x => { x.TheCallingAssembly(); x.WithDefaultConventions(); x.AddAllTypesOf<ICar>(); } ); ForRequestedType<IEnumerable<ICar>>().TheDefault.Is.ConstructedBy( x => ObjectFactory.GetAllInstances<ICar>()); I'm writing a unit test and have obtained a nested container off the ObjectFactory and have injected an instance using the Inject method. One of the instances of ICar should receive the injected type in its constructor. However it wasn't working and I tracked that down to the ObjectFactory.GetAllInstances() call which doesn't use my nested container. How can I get this to work? I also read about StructureMap autowiring arrays and IEnumerable instances but I couldn't get it to work. Is there a better way to rewrite the above registry code so that an instance of IEnumerable<TCar> will be created and use the injected type from my nested container?

    Read the article

  • Get Instance from StructureMap by Type Name

    - by JC Grubbs
    Is there any way to request an instance from the StructureMap ObjectFactory by the string name of the type? For example, it would be nice to do something like this: var thing = ObjectFactory.GetInstance("Thing"); The use case here is a messaging scenario in which the message is very generic and contains only the name of a task. The handler receives the message, gets the task name from the message and retrieves the Type of task runner from a configuration database. StructureMap scans all the assemblies in a directory and one of them will contain the Type returned from the config database which then needs to be instantiated. The other possibility is to grab a Type instance by doing the following: var type = Type.GetType("Thing"); But the problem there is the assembly may or may/not be loaded in the AppDomain so that reflection call isn't always possible.

    Read the article

  • Using ASP.NET MVC, Linq To SQL, and StructureMap causing DataContext to cache data

    - by Dragn1821
    I'll start by telling my project setup: ASP.NET MVC 1.0 StructureMap 2.6.1 VB I've created a bootstrapper class shown here: Imports StructureMap Imports DCS.Data Imports DCS.Services Public Class BootStrapper Public Shared Sub ConfigureStructureMap() ObjectFactory.Initialize(AddressOf StructureMapRegistry) End Sub Private Shared Sub StructureMapRegistry(ByVal x As IInitializationExpression) x.AddRegistry(New MainRegistry()) x.AddRegistry(New DataRegistry()) x.AddRegistry(New ServiceRegistry()) x.Scan(AddressOf StructureMapScanner) End Sub Private Shared Sub StructureMapScanner(ByVal scanner As StructureMap.Graph.IAssemblyScanner) scanner.Assembly("DCS") scanner.Assembly("DCS.Data") scanner.Assembly("DCS.Services") scanner.WithDefaultConventions() End Sub End Class I've created a controller factory shown here: Imports System.Web.Mvc Imports StructureMap Public Class StructureMapControllerFactory Inherits DefaultControllerFactory Protected Overrides Function GetControllerInstance(ByVal controllerType As System.Type) As System.Web.Mvc.IController Return ObjectFactory.GetInstance(controllerType) End Function End Class I've modified the Global.asax.vb as shown here: ... Sub Application_Start() RegisterRoutes(RouteTable.Routes) 'StructureMap BootStrapper.ConfigureStructureMap() ControllerBuilder.Current.SetControllerFactory(New StructureMapControllerFactory()) End Sub ... I've added a Structure Map registry file to each of my three projects: DCS, DCS.Data, and DCS.Services. Here is the DCS.Data registry: Imports StructureMap.Configuration.DSL Public Class DataRegistry Inherits Registry Public Sub New() 'Data Connections. [For](Of DCSDataContext)() _ .HybridHttpOrThreadLocalScoped _ .Use(New DCSDataContext()) 'Repositories. [For](Of IShiftRepository)() _ .Use(Of ShiftRepository)() [For](Of IMachineRepository)() _ .Use(Of MachineRepository)() [For](Of IShiftSummaryRepository)() _ .Use(Of ShiftSummaryRepository)() [For](Of IOperatorRepository)() _ .Use(Of OperatorRepository)() [For](Of IShiftSummaryJobRepository)() _ .Use(Of ShiftSummaryJobRepository)() End Sub End Class Everything works great as far as loading the dependecies, but I'm having problems with the DCSDataContext class that was genereated by Linq2SQL Classes. I have a form that posts to a details page (/Summary/Details), which loads in some data from SQL. I then have a button that opens a dialog box in JQuery, which populates the dialog from a request to (/Operator/Modify). On the dialog box, the form has a combo box and an OK button that lets the user change the operator's name. Upon clicking OK, the form is posted to (/Operator/Modify) and sent through the service and repository layers of my program and updates the record in the database. Then, the RedirectToAction is called to send the user back to the details page (/Summary/Details) where there is a call to pull the data from SQL again, updating the details view. Everything works great, except the details view does not show the new operator that was selected. I can step through the code and see the DCSDataContext class being accessed to update the operator (which does actually change the database record), but when the DCSDataContext is accessed to reload the details objects, it pulls in the old value. I'm guessing that StructureMap is causing not only the DCSDataContext class but also the data to be cached? I have also tried adding the following to the Global.asax, but it just ends up crashing the program telling me the DCSDataContext has been disposed... Private Sub MvcApplication_EndRequest(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.EndRequest StructureMap.ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects() End Sub Can someone please help?

    Read the article

  • Passing constructor arguments when using StructureMap

    - by Mosh
    Hello, I'm using StructureMap for my DI. Imagine I have a class that takes 1 argument like: public class ProductProvider : IProductProvider { public ProductProvider(string connectionString) { .... } } I need to specify the "connectionString at run-time when I get an instance of IProductProvider. I have configured StructureMap as follows: ForRequestedType<IProductProvider>.TheDefault.Is.OfConcreteType<ProductProvider>(). WithCtorArgument("connectionString"); However, I don't want to call EqualTo("something...") method here as I need some facility to dynamically specify this value at run-time. My question is: how can I get an instance of IProductProvider by using ObjectFactory? Currently, I have something like: ObjectFactory.GetInstance<IProductProvider>(); But as you know, this doesn't work... Any advice would be greatly appreciated.

    Read the article

  • Avoiding circular project/assembly references in Visual Studio with statically typed dependency conf

    - by svnpttrssn
    First, I want to say that I am not interested in debating about any non-helpful "answers" to my question, with suggestions to putting everything in one assembly, i.e. there is no need for anyone to provide webpages such as the page titled with "Separate Assemblies != Loose Coupling". Now, my question is if it somehow (maybe with some Visual Studio configuration to allow for circular project dependencies?) is possible to use one project/assembly (I am here calling it the "ServiceLocator" assembly) for retrieving concrete implementation classes, (e.g. with StructureMap) which can be referred to from other projects, while it of course is also necessary for the the ServiceLocator itself to refer to other projects with the interfaces and the implementations ? Visual Studio project example, illustrating the kind of dependency structure I am talking about: http://img10.imageshack.us/img10/8838/testingdependencyinject.png Please note in the above picture, the problem is how to let the classes in "ApplicationLayerServiceImplementations" retrieve and instantiate classes that implement the interfaces in "DomainLayerServiceInterfaces". The goal is here to not refer directly to the classes in "DomainLayerServiceImplementations", but rather to try using the project "ServiceLocator" to retrieve such classes, but then the circular dependency problem occurrs... For example, a "UserInterfaceLayer" project/assembly might contain this kind of code: ContainerBootstrapper.BootstrapStructureMap(); // located in "ServiceLocator" project/assembly MyDomainLayerInterface myDomainLayerInterface = ObjectFactory.GetInstance<MyDomainLayerInterface>(); // refering to project/assembly "DomainLayerServiceInterfaces" myDomainLayerInterface.MyDomainLayerMethod(); MyApplicationLayerInterface myApplicationLayerInterface = ObjectFactory.GetInstance<MyApplicationLayerInterface>(); // refering to project/assembly "ApplicationLayerServiceInterfaces" myApplicationLayerInterface.MyApplicationLayerMethod(); The above code do not refer to the implementation projects/assemblies ApplicationLayerServiceImplementations and DomainLayerServiceImplementations, which contain this kind of code: public class MyApplicationLayerImplementation : MyApplicationLayerInterface and public class MyDomainLayerImplementation : MyDomainLayerInterface The "ServiceLocator" project/assembly might contain this code: using ApplicationLayerServiceImplementations; using ApplicationLayerServiceInterfaces; using DomainLayerServiceImplementations; using DomainLayerServiceInterfaces; using StructureMap; namespace ServiceLocator { public static class ContainerBootstrapper { public static void BootstrapStructureMap() { ObjectFactory.Initialize(x => { // The two interfaces and the two implementations below are located in four different Visual Studio projects x.ForRequestedType<MyDomainLayerInterface>().TheDefaultIsConcreteType<MyDomainLayerImplementation>(); x.ForRequestedType<MyApplicationLayerInterface>().TheDefaultIsConcreteType<MyApplicationLayerImplementation>(); }); } } } So far, no problem, but the problem occurs when I want to let the class "MyApplicationLayerImplementation" in the project/assembly "ApplicationLayerServiceImplementations" use the "ServiceLocator" project/assembly for retrieving an implementation of "MyDomainLayerInterface". When I try to do that, i.e. add a reference from "MyApplicationLayerImplementation" to "ServiceLocator", then Visual Studio complains about circular dependencies between projects. Is there any nice solution to this problem, which does not imply using refactoring-unfriendly string based xml-configuration which breaks whenever an interface or class or its namespace is renamed ? / Sven

    Read the article

1 2 3 4  | Next Page >