My question is related to StructureMap and how to instantiate the object to share data between the hierarchy of objects within same http request context?
I have the below hierarchy of classes which generates some data.
IPageBuilder
-> IShipmentBuilder
-> IItemBuilder
-> IItemShippingOptionBuilder
-> IShippingOptionBuilder
-> IDeliveryMethodBuilder
-> IPaymentBuilder
-> ISummaryBuilder
In the client code: we use IPageBuilder.Build() will call the hierarchy of builders and returns an object.
Basically, We want to share some data from IItemBuilder to ISummaryBuilder. Eg., IItemBuilder makes an API call and the response should be shared also with ISummaryBuilder.
Tried Approach: Introduce an object such as IDataContext and pass it as argument in all above builders, but this seems to be tedious solution.
Expected Solution: Is there a way using StructureMap where I can inject IDataContext in IItemBuilder, store some data and the same data should be shared with ISummaryBuilder and it should happen for each http request context.
In short, is there a way to create a singleton per http request In structuremap?
Imported Package StructureMap.Web and Used HttpContextBasedLifeCycle for IDataContext and preserved a dictionary within DataContext concrete class to persist the data until the lifetime of httpContext.
Related
I am trying to introduce preferences DataStore in my Android Compose app and several tutorials suggest the use of Conext for keeping the reference to the DataStore instance. E.g. https://betterprogramming.pub/using-jetpack-preferences-datastore-more-effectively-414e1126cff7 and https://towardsdev.com/using-android-jetpack-datastore-with-jetpack-compose-6184338cf9c0 are such tutorials.
While it is possible to use Context for this, the Context is accessible from the Composables only and not from the ViewModels and repositories which are expected to be the most heavy users of DataStore. E.g. ViewModels can have functions that execute write functions of the DataStore. Repositories can read the saved URL from the DataStore.
So - Context is not the appropriate object to keep references to that DataStore, but which object is appropriate? Maybe AppContainer?
DataStore is expected to be application wide singleton. Maybe preferencesDataStore is already guaranteeing this?
I.e. maybe I can call
myLocalVariable: DataStore<Preferences> by preferencesDataStore(name = "my_app_configuration")
in each of my ViewModel or repository and then I can use myLocalVariable in those modules freely and the perferencesDataStore guarntees that there is only one DataStore instance for the entire application?
Using dependency inversion and abstraction you can keep Android code out of your repository classes as they should and using dependency injection you can pass Context to implementation, assuming Dagger is used you can bind your interface to implementation using #Binds annotation
create an Interface for write/read operations
interface MyDataStore {
fun read()
fun write()
}
an implementation that takes Context as argument
class DataStoreImpl(context:Context):MyDataStore {
// Implementation
}
If you define your repositories or ViewModels as
class Repository(myDataStore: MyDataStore)
you will be able to remove coupling to context or DataStore in your classes. This way if google decides to introduce another class for storage in the future you can easily replace it with existing one or can implement multiple implementation versions and change to required one using polymorphism
My suggestion would be to use Hilt to inject code into viewModel
Here is a example.
#Module
#InstallIn(SingletonComponent::class)
object Singleton {
/**
* Provides the Singleton Implementation of Preferences DataStore.
*/
#Provides
#Singleton
fun preferences(#ApplicationContext context: Context) = Preferences(context)
}
Here the Preferences is a wraaper around DataStore.
Now you inject the instance of Preference into the viewModel easily.
Here I have created a lib to make the integration with compose easily.
here is the dependency from jitpack the io
implementation 'com.github.prime-zs:support:Tag'
Preference
Thanks in advance for any help.
I have a caching service I've implemented with a core data stack in Swift 3.1. The exposed interface conforms to this protocol:
protocol WeekForecastCacheService {
func add(cacheModels: [DayForecastCacheModel])
func get(cityId: Int, callback: #escaping ([DayForecastCacheModel]?) -> () )
}
Ideally I want the internals of my core data stack to stay private.
However I also want to be able to unit test the class. Specifically the exposed interface. Because the core data stack is persistent I want to be able to delete every entity (a reset if you will to start tests in a known state). How do I go about doing this while keeping the unit test implementation outside of my main target.
Ideally I would also like my tests to be independent of implementation...
I'm thinking along the lines of the following but could do with some advice:
Add a delete all function to the cache class
Use a class extension and implement the functionality there - it would mean a fair amount of copy paste
Change private functions / variables to be internal giving enough access to easily create a delete all function in a class extension
Stop worrying because only protocols are used by classes consuming the service so it doesn't matter if functions and properties within the class are not private
When unit testing Core Data, a typical approach is to use the in-memory store type to effectively remove the "persistent" part of Core Data. With an in-memory store you get all of Core Data's usual capabilities, but the persistent store isn't written to a file so it always starts off empty. That gets you to a known starting state. If necessary you can pre-load some other known state into the in-memory store before beginning the test.
The key for this is NSInMemoryStoreType. If you're setting explicitly adding the persistent store, that would be the type value when calling addPersistentStore(ofType:configurationName:at:options:). If you're using NSPersistentContainer, you'd include the store type in the persistentStoreDescriptions property.
In an application I have the following components (among others):
MyDbContext : Entity framework data access
DBResourceProviderFactory : A custom ResourceProviderFactory providing a custom IResourceProvider (called DBResourceProvider...)
Other services
StructureMap
The custom resource provider is looking resources up in the db using MyDbContext, injected similarly as described in this SO answer.
The MyDbContext is also used in various other services, and since it is a web application, I use StructureMaps HttpContextScoped method to limit the lifetime of MyDbContext to the lifetime of the request (see an other SO question and its answer on this subject):
x.For<MyDbContext>().HttpContextScoped();
However, it seems that the lifetime of an IResourceProvider is not limited to a single http request. Therefore, DBResourceProvider keeps hanging onto a MyDbContext reference which will be disposed after the first request.
How can I handle this lifetime mismatch - have StructureMap return a transient MyDbContext for IDbResourceProvider while returning HttpContext-scoped instances to all other services?
Do I need two different implementations to do that? A marker interface?
Or is it a bad idea to use Entity Framework to look up localized resources in the first place (performance etc.)?
If you have a service that has (or needs to have) a long lifetime than (one of) its dependencies, the general solution is to use a factory to get those dependencies.
In your situation the solution might be simple. When your DBResourceProvider is defined in your composition root of your MVC application, it would simply succeed to use the DependencyResolver.Current.GetService method to get the MyDbContext.
When the DBResourceProvider service isn't part of the composition root (for instance because it contains business logic that you need to test), you could either extract that logic into its own class, to allow the service to be in the composition root, or you can inject a (singleton) factory (for instance IDbContextFactory or Func<MyDbContext>) that allows you to get the proper instance to be resolved.
I'm putting a project together with Spring.NET and Caliburn v2. I have some objects that I'm trying to instantiate, but not sure how to go about it.
I have been using Caliburn's IoC aspect annotations (Singleton and PerRequest) to get objects into the Spring context. The problem with this is that I have two objects, A and B, where Object B is a subclass of Object A (meaning B is also an A). This means that if I register both, Spring complains of ambiguity when an object of type A is requested. To get around this, I could stop using Caliburn's IoC aspects to register the objects and instead register them in the Spring context XML files. That way I can specify a named object in the Spring context file to use in the constructor of object C, which needs an object of type B injected.
However, this creates a new problem. Object B needs the Caliburn window manager to be injected (which is not available to the Spring container at the time when the objects listed in the context XML files are instantiated, but only later, after Caliburn has loaded and added its own objects to the Spring container).
I could simply remove the inheritance and let some code duplication occur between objects A and B, but then what would be the point of doing OO programming? Otherwise I guess I'm looking for a way to specify objects in Spring.NET context XML, but keep them from being resolved until after Caliburn has loaded.
Any ideas?
I'm not familiar with Caliburn but if you want to delay instantiation then you could mark your objects in xml as lazy-init, like this:<object id="foo" type="..." lazy-init="true"/>
This way they will be instantiated when you first request them
I managed to solve this by maintaining a separate list of caliburn-dependent spring context XML files. I loaded these into the ApplicationContext object by adding the following code at the beginning of the overridden DisplayRootView() method in my application's bootstrapper:
var objectDefinitionReader = new XmlObjectDefinitionReader(applicationContext);
objectDefinitionReader.LoadObjectDefinitions(GetCaliburnDependentContextFiles());
applicationContext.Refresh();
Greetings,
Trying to sort through the best way to provide access to my Entity Manager while keeping the context open through the request to permit late loading. I am seeing a lot of examples like the following:
public class SomeController
{
MyEntities entities = new MyEntities();
}
The problem I see with this setup is that if you have a layer of business classes that you want to make calls into, you end up having to pass the manager as a parameter to these methods, like so:
public static GetEntity(MyEntities entityManager, int id)
{
return entityManager.Series.FirstOrDefault(s => s.SeriesId == id);
}
Obviously I am looking for a good, thread safe way, to provide the entityManager to the method without passing it. The way also needs to be unit testable, my previous attempts with putting it in Session did not work for unit tests.
I am actually looking for the recommended way of dealing with the Entity Framework in ASP .NET MVC for an enterprise level application.
Thanks in advance
Entity Framework v1.0 excels in Windows Forms applications where you can use the object context for as long as you like. In asp.net and mvc in particular it's a bit harder. My solution to this was to make the repositories or entity managers more like services that MVC could communicate with. I created a sort of generic all purpose base repository I could use whenever I felt like it and just stopped bothering too much about doing it right. I would try to avoid leaving the object context open for even a ms longer than is absolutely needed in a web application.
Have a look at EF4. I started using EF in production environment when that was in beta 0.75 or something similar and had no real issues with it except for it being "hard work" sometimes.
You might want to look at the Repository pattern (here's a write up of Repository with Linq to SQL).
The basic idea would be that instead of creating a static class, you instantiate a version of the Repository. You can pass in your EntityManager as a parameter to the class in the constructor -- or better yet, a factory that can create your EntityManager for the class so that it can do unit of work instantiation of the manager.
For MVC I use a base controller class. In this class you could create your entity manager factory and make it a property of the class so deriving classes have access to it. Allow it to be injected from a constructor but created with the proper default if the instance passed in is null. Whenever a controller method needs to create a repository, it can use this instance to pass into the Repository so that it can create the manager required.
In this way, you get rid of the static methods and allow mock instances to be used in your unit tests. By passing in a factory -- which ought to create instances that implement interfaces, btw -- you decouple your repository from the actual manager class.
Don't lazy load entities in the view. Don't make business layer calls in the view. Load all the entities the view will need up front in the controller, compute all the sums and averages the view will need up front in the controller, etc. After all, that's what the controller is for.